我有以下代码:
public void button_login(View view) {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { /* User clicked OK button */ }
});
// Preserve EditText values.
EditText ET_username = (EditText) findViewById(R.id.username);
EditText ET_password = (EditText) findViewById(R.id.password);
String str_username = ET_username.toString();
String str_password = ET_password.toString();
// Intercept missing username and password.
if(str_username.length() == 0) {
builder.setMessage(R.string.hint_username_empty);
AlertDialog dialog = builder.create();
dialog.show();
}
}
我有一个包含两个EditText-Views和一个按钮的活动。当我单击按钮时,将调用显示的方法。
我的问题: AlertDialog没有出现!
当我把创建和节目放在这样的开头时:
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { /* User clicked OK button */ }
});
builder.setMessage(R.string.hint_username_empty);
AlertDialog dialog = builder.create();
dialog.show();
// Preserve EditText values.
EditText ET_username = (EditText) findViewById(R.id.username);
EditText ET_password = (EditText) findViewById(R.id.password);
String str_username = ET_username.toString();
String str_password = ET_password.toString();
// Intercept missing username and password.
if(str_username.length() == 0) {
}
}
然后对话框出现。
为什么对话框没有首先显示出来?
答案 0 :(得分:2)
这是因为EditText.toString()
不会返回文本。请改用EditText.getText().toString()
。您还应该在if语句之前和之后添加一些日志语句,以便更好地了解正在发生的事情。
答案 1 :(得分:1)
问题在于以下几行:
String str_username = ET_username.toString();//is never empty
String str_password = ET_password.toString();//is never empty
尝试以下应该运行的代码
String str_username = ET_username.getText().toString();
String str_password = ET_password.getText().toString();