Java 以编程方式访问AlertDialog PositiveButton
我使用AlertDialog要求用户在长按视图时输入数值。它使用Android软键盘。为了获得更好的用户体验,我希望键盘上的Enter按钮能够通过编程方式单击警报对话框的肯定按钮并运行onClick。这真的很尴尬,因为我在对话框对象中找不到任何对正按钮的引用。用于说明的代码:Java 以编程方式访问AlertDialog PositiveButton,java,android,android-alertdialog,Java,Android,Android Alertdialog,我使用AlertDialog要求用户在长按视图时输入数值。它使用Android软键盘。为了获得更好的用户体验,我希望键盘上的Enter按钮能够通过编程方式单击警报对话框的肯定按钮并运行onClick。这真的很尴尬,因为我在对话框对象中找不到任何对正按钮的引用。用于说明的代码: customStakeView.setOnLongClickListener(new View.OnLongClickListener() { @Override public bo
customStakeView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Custom Stake");
customStakeSet = false;
// Set up the input
final EditText input = new EditText(context);
input.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
// Specify the type of input expected;
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if(keyEvent.getAction() == KeyEvent.ACTION_DOWN){
if(!input.getText().toString().equals("")){
switch (keyCode){
case KeyEvent.KEYCODE_ENTER:
//Positive Button Outcome
}
}
}
return false;
}
});
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newStake = input.getText().toString();
if (!newStake.equals("")) {
newStake = newStake.replaceAll("[^\\d.]", ""); //strip down to currency format
customStake = new Stake(newStake);
customStakeSet = true;
deselectAll();
selectCustomStake();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
});
我已经捕获了KeyEvent,如果这是一个通过XML添加的按钮,或者甚至是用变量定义的按钮,那么我很容易就能做到
button.performClick();
但AlertDialog似乎没有这样的参考
编辑:
从中,使用getButtonwhichButton
获取对话框中使用的按钮之一。如果指定的按钮不存在或对话框尚未完全创建(例如,通过show或create),则返回null
可以是哪个按钮,也可以是您指定的任何其他按钮
下面是它的截图
您没有捕获.create方法返回的AlertDialog。getButton对生成器不可用,但对AlertDialog对象可用
builder.setPositiveButton(...);
// you're missing this
final AlertDialog alertDialog = builder.create();
// then, use it like this
alertDialog.getButton(DialogInterface.Button_POSITIVE).performClick();
奇怪的我似乎无法调用警报对话框对象生成器上的getButton。我是不是遗漏了什么?你必须先建立对话。调用builder.create。然后,使用此按钮从创建的AlertDialog获取按钮。阅读我的答案,它说若并没有创建对话框,按钮将是空的。似乎无法让这个工作。调用builder.create不会为AlertDialog提供任何新的getter。我在答案中添加了一个屏幕截图。您的逻辑和文档似乎是正确的,但getButton方法似乎不可用。我添加了一个新的屏幕截图。我看不出代码示例之间有任何主要区别