如果我的对话框有多个按钮,如何将 OnClickListener 放入切换案例(或if / else),如下所示:
我想让用户选择值来指定静态变量输入
public class ActivityInput extends Activity {
public static String input;
public void selectValue (final int x) {
btn = (Button) findViewById(x);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Display dialog with 3 button for user to select the values
final Dialog dialog1 = new Dialog(input.this);
dialog1.setTitle("Select a Number");
dialog1.setContentView(R.layout.dialog);
dialog1.show();
button1 = (Button) dialog1.findViewById(R.id.val1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Button p1_btn = (Button) findViewById(x);
input = "1";
p1_btn.setText("1");
dialog1.dismiss();
}
});
button2 = (Button) dialog1.findViewById(R.id.val2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Button p1_btn = (Button) findViewById(x);
input = "2";
p1_btn.setText("2");
dialog1.dismiss();
}
});
button3 = (Button) dialog1.findViewById(R.id.val3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Button p1_btn = (Button) findViewById(x);
input = "3";
p1_btn.setText("2");
dialog1.dismiss();
}
});
}
});
}
}
希望你指导我尽快帮助我!
非常感谢你。
答案 0 :(得分:3)
没有xml的简单解决方案:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setItems(new CharSequence[]
{"button 1", "button 2", "button 3", "button 4"},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
Toast.makeText(context, "clicked 1", 0).show();
break;
case 1:
Toast.makeText(context, "clicked 2", 0).show();
break;
case 2:
Toast.makeText(context, "clicked 3", 0).show();
break;
case 3:
Toast.makeText(context, "clicked 4", 0).show();
break;
}
}
});
builder.create().show();
答案 1 :(得分:3)
public void verticalAlert (){
String[] array = {"item01","item02","item03"};
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
builder.setTitle("Test")
.setItems(array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
// case item 1 do...
break;
case 1:
// case item 2 do...
break;
case 2:
// case item 3 do...
break;
}
}
});
builder.show();
}