我有以下代码:
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没有显示!
当我像这样把create and show放在开头时:
// 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) {
}
}
对话框出现。
你知道为什么对话框一开始没有出现吗?
这是因为EditText.toString()
不返回文本。使用EditText.getText().toString()
代替。您还应该在if语句之前和中添加一些日志语句,以便您可以更好地理解发生了什么。
问题出在以下几行:
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();