Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用单选复选框在AlertDialog中选择条目?_Android_Android Alertdialog - Fatal编程技术网

Android 如何使用单选复选框在AlertDialog中选择条目?

Android 如何使用单选复选框在AlertDialog中选择条目?,android,android-alertdialog,Android,Android Alertdialog,我有一个警报对话框,有一个单选列表和两个按钮:一个OK按钮和一个cancel按钮。下面的代码显示了我是如何实现它的 private final Dialog createListFile(final String[] fileList) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Compare with:"); builder.setSingleChoiceIte

我有一个警报对话框,有一个单选列表和两个按钮:一个
OK
按钮和一个
cancel
按钮。下面的代码显示了我是如何实现它的

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

我的目标是在点击
OK
按钮时获取所选单选按钮的名称。我试图将字符串保存在变量中,但在内部类中,只能访问最终变量。有没有办法避免使用最终变量来存储所选单选按钮?

使用最终变量显然不起作用(因为在声明时只能分配一次)。所谓的“全局”变量通常是一种代码味道(特别是当它们成为活动类的一部分时,通常是创建AlertDialogs的地方)。
final CharSequence[] choice = {"Choose from Gallery","Capture a photo"};

int from; //This must be declared as global !

AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Upload Photo");
alert.setSingleChoiceItems(choice, -1, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (choice[which] == "Choose from Gallery") {
            from = 1;
        } else if (choice[which] == "Capture a photo") {
            from = 2;
        }
    }
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (from == 0) {
            Toast.makeText(activity, "Select One Choice", 
                        Toast.LENGTH_SHORT).show();
        } else if (from == 1) {
            // Your Code
        } else if (from == 2) {
            // Your Code
        }
    }
});
alert.show();
更干净的解决方案是将DialogInterface对象强制转换为AlertDialog,然后调用getListView().GetCheckEditePosition()。像这样:

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

这个问题已经得到了很好的回答,但我一直从谷歌那里找到这个答案,我想分享一个非匿名类的解决方案。我自己更喜欢可重用类,可能对其他人有帮助

在本例中,我使用了一个
DialogFragment
实现,并通过回调方法检索一个值

通过创建公共接口

public interface OnDialogSelectorListener {
    public void onSelectedOption(int selectedIndex);
}
另外,
DialogFragment
实现了
DialogInterface.OnClickListener
,这意味着您可以将已实现的类注册为正在创建的
DialogFragment
的OnClickListener

比如说

public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());

    builder.setTitle(R.string.select);
    builder.setSingleChoiceItems(mResourceArray, mSelectedIndex, this);
    builder.setPositiveButton(R.string.ok, this);
    builder.setNegativeButton(R.string.cancel, this);
    return builder.create();
}
线路

builder.setSingleChoiceItems(mresourceray,mSelectedIndex,this)

使用mResourceArray中存储的资源数组中的选项创建选项对话框。这也会从mSelectedIndex中存储的内容中预先选择一个选项索引,最后它会将
This
本身设置为OnClickListener。(如果本段有点混乱,请参阅结尾的完整代码)

现在,OnClick方法就是从对话框中获取值的方法

@Override
public void onClick(DialogInterface dialog, int which) {

    switch (which) {
        case Dialog.BUTTON_NEGATIVE: // Cancel button selected, do nothing
            dialog.cancel();
            break;

        case Dialog.BUTTON_POSITIVE: // OK button selected, send the data back
            dialog.dismiss();
            // message selected value to registered callbacks with the
                    // selected value.
            mDialogSelectorCallback.onSelectedOption(mSelectedIndex);
            break;

        default: // choice item selected
                    // store the new selected value in the static variable
            mSelectedIndex = which;
            break;
    }
}
这里发生的事情是,当一个项目被选中时,它存储在一个变量中。如果用户单击“取消”按钮,则不会发回任何更新,也不会发生任何更改。如果用户单击OK按钮,它会将值返回到通过所创建的回调创建它的
活动

例如,下面是如何从
片段活动
创建对话框

final SelectorDialog sd = SelectorDialog.newInstance(R.array.selector_array, preSelectedValue);
sd.show(getSupportFragmentManager(), TAG);
在这里,资源数组_R.array.selector _array uu是要在对话框中显示的字符串数组,preSelectedValue是打开时要选择的索引

最后,您的
FragmentActivity
将实现
OnDialogSelectorListener
,并将收到回调消息

public class MyActivity extends FragmentActivity implements OnDialogSelectorListener {
// ....

    public void onSelectedOption(int selectedIndex) {
        // do something with the newly selected index
    }
}
我希望这对某人有帮助,因为我花了很多时间才理解它。这里是这种类型的带有回调的
对话框片段
的完整实现

来自评论的问题如何从
片段
而不是
活动
调用此问题

final SelectorDialog sd = SelectorDialog.newInstance(R.array.selector_array, preSelectedValue);
sd.show(getSupportFragmentManager(), TAG);
首先对
对话框片段进行一些更改

删除
onAttach
事件,因为在这种情况下,这不是最简单的方法

添加一个新方法以添加对回调的引用

public void setDialogSelectorListener (OnDialogSelectorListener listener) {
    this.mListener = listener;
}
片段中实现侦听器

public class MyFragment extends Fragment implements SelectorDialog.OnDialogSelectorListener {
// ....

    public void onSelectedOption(int selectedIndex) {
        // do something with the newly selected index
    }
}
现在创建一个新实例,并传入对
片段的引用以使用它

final SelectorDialog sd = SelectorDialog.newInstance(R.array.selector_array, preSelectedValue);
// this is a reference to MyFragment
sd.setDialogSelectorListener(this);
// mActivity is just a reference to the activity attached to MyFragment
sd.show(this.mActivity.getSupportFragmentManager(), TAG);
试试这个

final String[] fonts = {"Small", "Medium", "Large", "Huge"};

AlertDialog.Builder builder = new AlertDialog.Builder(TopicDetails.this);
builder.setTitle("Select a text size");
builder.setItems(fonts, new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {
    if ("Small".equals(fonts[which])) {
      Toast.makeText(MainActivity.this,"you nailed it", Toast.LENGTH_SHORT).show();
    }
    else if ("Medium".equals(fonts[which])) {
      Toast.makeText(MainActivity.this,"you cracked it", Toast.LENGTH_SHORT).show();
    }
    else if ("Large".equals(fonts[which])){
      Toast.makeText(MainActivity.this,"you hacked it", Toast.LENGTH_SHORT).show();
    }
    else if ("Huge".equals(fonts[which])){
     Toast.makeText(MainActivity.this,"you digged it", Toast.LENGTH_SHORT).show();
    }
  // the user clicked on colors[which]
  }
});
builder.show();

正如其他人指出的,实现'com.google.android.material:material:1.0.0'更简单

有关更多信息,请参阅本材料指南


from变量不是最终变量,您不能在内部类中使用它。如果我想记住选择了什么,下次打开对话框时,选择是预先选择的,该怎么办?@SiKni8您可以存储selectedPosition(可能作为活动的实例变量),然后调用getListView().setItemChecked()下次打开对话框时。我得到了selectedPosition,但不确定在哪里调用.setItemChecked()。这里是我的问题:提示:您可以使用
android.R.string.ok
作为
R.string.ok\u按钮\u标签
谢谢您的解释。您如何实现回调,以便在侦听器触发时通知
片段而不是
活动
?我已经添加了一个解释,说明如何在
片段
CharSequence[] choices = {"Choice1", "Choice2", "Choice3"};
boolean[] choicesInitial = {false, true, false};
AlertDialog.Builder alertDialogBuilder = new MaterialAlertDialogBuilder(getContext())
    .setTitle(title)
    .setPositiveButton("Accept", null)
    .setNeutralButton("Cancel", null)
    .setMultiChoiceItems(choices, choicesInitial, new DialogInterface.OnMultiChoiceClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which, boolean isChecked) {

      }
    });
alertDialogBuilder.show();