保持从alertdialog到主代码的变量

时间:2014-09-25 14:20:18

标签: android

代码示例显示了alertdialog。我想把用户选择到button1。我无法理解如何传递变量" arg1"到主要代码:

public class MainActivity extends ActionBarActivity {
    private Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) { 

            alertSingleChoiceItems();

              }
            });
        // I need put here my variable:
        button1.setText(""+???);
    }

public void alertSingleChoiceItems(){

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 builder.setTitle("Choose One")

    .setSingleChoiceItems(R.array.choices, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {

        }

    })

以下是用户必须单击确定以设置选择的原因:

    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {

            int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
            showToast("selectedPosition: " + selectedPosition);
        }
    })

    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {

        }
    })
    .show();
}

3 个答案:

答案 0 :(得分:0)

您只需在对话框的onClick中设置按钮即可。

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose One");
builder.setSingleChoiceItems(R.array.choices, 0, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        button1.setText(""+arg1);
    }
});
builder.create().show();

您不能按照建议设置它,因为设置Button文本的代码将在alertSingleChoiceItems()之前运行;被称为。

答案 1 :(得分:0)

您可以使用全局静态整数变量并在按钮单击中将arg1指定给它...类似

private static int x = 0;

.setSingleChoiceItems(R.array.choices, 0, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface arg0, int arg1) {
       x = arg1;
    }

})

编辑:

如果你想直接设置按钮文本,那么Knossos的答案大多比我的回答更有帮助..

答案 2 :(得分:0)

只需在主类中创建一个公共(非必要的静态)变量,如下所示:

public class MainActivity extends ActionBarActivity {
         private Button button1;

         public int arg;

然后:

public void onClick(DialogInterface arg0, int arg1) {
     arg = arg1;
    }