Android的对话框单选得到无线电选择无线电、对话框、单选、Android

2023-09-05 07:41:21 作者:原野的清风

在code的方法贴在下面,我创建了一个单项选择列表两个按钮,一个警告对话框:一个OK按钮和一个取消按钮。我的目标是让你的时候preSS确定按钮你所选择的单选按钮的名称。

The method in the code posted below, I create an alert dialog with a single-choice list with two buttons: an OK button and a cancel button. My goal is to make when you press the OK button you get the name of the selected radio button.

private final Dialog createListFile(final String[] fileList) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Compare with:");
    builder.setSingleChoiceItems(fileList, -1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
             Log.d(TAG,"The wrong button was tapped: "+fileList[whichButton]);   

        }
    });
   builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
    });
    return builder.create();
}

我想保存在字符串中的变量,但在一个内部类只能使用最后的变量。我该如何解决这个问题?

I tried to save the string in a variable, but in an inner class can only use final variables. How can I fix it?

推荐答案

使用最后一个变量显然是不行的(因为它只能被分配一次,在声明时)。所谓全局变量通常一个code气味(尤其是当它们成为一个活动类,通常是在其中创建AlertDialogs的一部分)。 清洁工解决方案是将DialogInterface对象强制转换为AlertDialog,然后调用getListView()。getCheckedItemPosition()。像这样的:

Using a final variable obviously won't work (since it can only be assigned once, at declaration time). So-called "global" variables are usually a code smell (especially when they become part of an Activity class, which is usually where AlertDialogs are created). The cleaner solution is to cast the DialogInterface object to an AlertDialog and then call getListView().getCheckedItemPosition(). Like this:

new AlertDialog.Builder(this)
        .setSingleChoiceItems(items, 0, null)
        .setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
                int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
                // Do something useful withe the position of the selected radio button
            }
        })
        .show();
 
精彩推荐
图片推荐