我有一个自定义警报对话框,EditText和正负按钮给用户4位数字。它工作正常,但我想做一些事情,当用户输入4位数字并点击" DONE"软键盘按钮,做一些像正面按钮的代码,然后关闭对话框。这是我的代码:
final AlertDialog.Builder builder = new AlertDialog.Builder(ConversationActivity.this);
builder.setTitle("Test");
final EditText input = new EditText(ConversationActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setImeOptions(EditorInfo.IME_ACTION_DONE);
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE){
// what should I want.?!
}
return false;
}
});
int maxLength = 4;
input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
感谢。
答案 0 :(得分:1)
你可以这样做: -
1)在您的活动中全局声明警报Dialog实例
..
..
//Alert Dialog instance
private AlertDialog alertDialog;
int maxLength = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
..
..
并使用该实例来关闭警报对话框
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("Test");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setImeOptions(EditorInfo.IME_ACTION_DONE);
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// This is How you do it want.?!
if (input.getText().toString().length() == maxLength) {
//Use alert Dialog instance to dismiss
alertDialog.dismiss();
Toast.makeText(getApplicationContext(),
"You Entered" + input.getText().toString(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Please Enter 4 Digits", Toast.LENGTH_SHORT)
.show();
}
}
return false;
}
});
input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
maxLength) });
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"You Entered" + input.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// This should I want.?!
dialog.cancel();
}
});
//Assign alert Dialog instance like this..
alertDialog = builder.show();
希望这对你有用!