Android 保持从alertdialog到主代码的变量可用

Android 保持从alertdialog到主代码的变量可用,android,Android,示例代码显示了一个alertdialog。我想把用户的选择按钮1。我无法理解如何将变量“arg1”传递给主代码: public class MainActivity extends ActionBarActivity { private Button button1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceSta

示例代码显示了一个alertdialog。我想把用户的选择按钮1。我无法理解如何将变量“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();
}

您只需在单击对话框时设置按钮即可

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();

您不能按照建议进行设置,因为设置按钮文本的代码将在alertSingleChoiceItems()之前运行;调用。

您可以获取一个全局静态整数变量,并在按钮单击中为其分配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的答案比我的答案更有用。

只需在主类中创建一个公共(而不是静态)变量,如下所示:

public class MainActivity extends ActionBarActivity {
         private Button button1;

         public int arg;
然后:


非常感谢。但是我需要在主代码中使用该变量:-)该变量不需要是静态的。作为补充。@Knossos是的。你是对的。。但是静态可能比简单变量更友好。谢谢你的建议:)
public void onClick(DialogInterface arg0, int arg1) {
     arg = arg1;
    }