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.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 按钮时获取所选单选按钮的名称。我试图将字符串保存在变量中,但在内部类中只能访问最终变量。有没有办法避免使用最终变量来存储选定的单选按钮?

最佳答案

使用 final 变量显然是行不通的(因为它只能在声明时分配一次)。所谓的“全局”变量通常是一种代码味道(尤其是当它们成为 Activity 类的一部分时,通常是创建 AlertDialogs 的地方)。 更简洁的解决方案是将 DialogInterface 对象转换为 AlertDialog,然后调用 getListView().getCheckedItemPosition()。像这样:

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

关于android - 如何使用单选复选框android在AlertDialog中选择一个条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5660887/

相关文章:

java - 如何在 Firebase 中连接数据库条目和存储条目?

android - 可以更改主题的某些方面(颜色)

Android ProgressDialog 不显示

android - 无法访问来自不同类的值

java - 如何停止按下背面的媒体播放器,无论它是否正在播放?

Android:如何使用IdlingResource等待后台任务(Espresso)

Android:快速滚动时 Gridview 变为空白

android - 在 Android Kotlin 中无法访问 dialog.getButton()

android - 如何防止屏幕方向改变从相机 Intent 返回(SGS3)

c# - 从 ViewModel 到 View Xamarin 的 MVVMCross Calling 函数