全局初始化控件在不同的方法中变为 null



我在顶部声明了几个变量,这些变量正在onCreate方法中初始化,当我在不同的方法中使用它们时,它们会返回null

下面的代码始终显示"控件变为空值..">结果。

public class MainActivity extends AppCompatActivity
{
EditText txtUsername,txtPass;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText txtUsername = (EditText) findViewById(R.id.txtUserName);
EditText txtPass = (EditText) findViewById(R.id.txtPassword);
Button btnLogin=(Button)findViewById(R.id.btnLogin);
txtUsername.setText("Arvind");
txtPass.setText("1234");
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doLogin();
}
});
}
void doLogin()
{
if(txtUsername!=null || txtPass!=null) {
if (txtUsername.getText() != null && txtPass.getText() != null) {
Toast.makeText(this, "Successfully logged in..", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Username or Password can't be empty..", Toast.LENGTH_SHORT).show();
}
}else
{
Toast.makeText(this, "Controls becomes null..", Toast.LENGTH_SHORT).show();
}
}
}

如何解决此问题?

你做错了, 如果要声明为全局变量,那么为什么要在方法中再次在局部声明新变量onCreate()

您必须使用与声明全局相同的变量,而不是创建新变量。

看看这个

public class MainActivity extends AppCompatActivity
{
EditText txtUsername,txtPass;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUsername = (EditText) findViewById(R.id.txtUserName);
txtPass = (EditText) findViewById(R.id.txtPassword);
btnLogin=(Button)findViewById(R.id.btnLogin);
txtUsername.setText("Arvind");
txtPass.setText("1234");
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doLogin();
}
});
}
void doLogin()
{
if(txtUsername!=null || txtPass!=null) {
if (txtUsername.getText() != null && txtPass.getText() != null) {
Toast.makeText(this, "Successfully logged in..", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Username or Password can't be empty..", Toast.LENGTH_SHORT).show();
}
}else
{
Toast.makeText(this, "Controls becomes null..", Toast.LENGTH_SHORT).show();
}
}
}

相关内容

  • 没有找到相关文章

最新更新