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

如何解决如何使用单选复选框android在AlertDialog中选择条目?

| 我有一个带有单选列表和两个按钮的警报对话框:一个“ 0”按钮和一个“ 1”按钮。下面的代码显示了我如何实现它。
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\",int whichButton) {}
  });

  builder.setNegativeButton(\"Cancel\",int whichButton) {}
  });

  return builder.create();
}
我的目标是在轻按“ 0”按钮时获得所选单选按钮的名称。我试图将字符串保存在变量中,但是在内部类内部,只能访问最终变量。有没有一种方法可以避免使用最终变量来存储所选的单选按钮?     

解决方法

使用最终变量显然是行不通的(因为在声明时只能分配一次)。所谓的\“ global \”变量通常是代码的味道(尤其是当它们成为Activity类的一部分时,通常在其中创建AlertDialogs)。 较干净的解决方案是将DialogInterface对象转换为AlertDialog,然后调用getListView()。getCheckedItemPosition()。像这样:
new AlertDialog.Builder(this)
        .setSingleChoiceItems(items,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();
    ,这已经很好地回答了,但是我一直从Google那里找到这个答案,我想分享一个非匿名的类解决方案。我本人更喜欢可重用的类,可能会对其他人有所帮助。 在此示例中,我使用
DialogFragment
实现,并通过回调方法检索值。 可以通过创建公共接口来完成从Dialog获取值的回调方法。
public interface OnDialogSelectorListener {
    public void onSelectedOption(int selectedIndex);
}
同样,“ 5”实现了“ 8”,这意味着您可以将已实现的类注册为正在创建的“ 5”的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(mResourceArray,this);
创建一个选择对话框,其中包含来自mResourceArray中存储的资源数组中的选项。这还将从mSelectedIndex中存储的内容中预选择一个选项索引,最后将ѭ12本身设置为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;
    }
}
这里发生的是,当一个项目被选中时,它存储在一个变量中。如果用户单击“取消”按钮,则不会发送任何更新,也不会进行任何更改。如果用户单击“确定”按钮,它将通过创建的回调将值返回到创建它的ѭ14。 例如,以下是从
FragmentActivity
创建对话框的方法。
final SelectorDialog sd = SelectorDialog.newInstance(R.array.selector_array,preSelectedValue);
sd.show(getSupportFragmentManager(),TAG);
在这里,资源数组_R.array.selector_array_是要在对话框中显示的字符串数组,而preSelectedValue是在打开时选择的索引。 最后,您的
FragmentActivity
将实现
OnDialogSelectorListener
并将收到回调消息。
public class MyActivity extends FragmentActivity implements OnDialogSelectorListener {
// ....

    public void onSelectedOption(int selectedIndex) {
        // do something with the newly selected index
    }
}
我希望这对某人有帮助,因为我花了很多时间来理解它。这是带有回调的ѭ5full的完整实现。
public class SelectorDialog extends DialogFragment implements OnClickListener {
    static final String TAG = \"SelectorDialog\";

    static int mResourceArray;
    static int mSelectedIndex;
    static OnDialogSelectorListener mDialogSelectorCallback;

    public interface OnDialogSelectorListener {
        public void onSelectedOption(int dialogId);
    }

    public static DialogSelectorDialog newInstance(int res,int selected) {
        final DialogSelectorDialog dialog  = new DialogSelectorDialog();
        mResourceArray = res;
        mSelectedIndex = selected;

        return dialog;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mDialogSelectorCallback = (OnDialogSelectorListener)activity;
        } catch (final ClassCastException e) {
            throw new ClassCastException(activity.toString() + \" must implement OnDialogSelectorListener\");
        }
    }

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

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

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

        switch (which) {
            case Dialog.BUTTON_NEGATIVE:
                dialog.cancel();
                break;

            case Dialog.BUTTON_POSITIVE:
                dialog.dismiss();
                // message selected value to registered calbacks
                mDialogSelectorCallback.onSelectedOption(mSelectedIndex);
                break;

            default: // choice selected click
                mSelectedIndex = which;
                break;
        }

    }
}
来自注释的问题如何用
Fragment
而不是ѭ14call称呼它。 首先对ѭ5进行一些更改。 删除“ 25”事件,因为在这种情况下这不是最简单的方法。 添加新方法以添加对回调的引用
public void setDialogSelectorListener (OnDialogSelectorListener listener) {
    this.mListener = listener;
}
在您的ѭ22中实现监听器
public class MyFragment extends Fragment implements SelectorDialog.OnDialogSelectorListener {
// ....

    public void onSelectedOption(int selectedIndex) {
        // do something with the newly selected index
    }
}
现在创建一个新实例,并将引用传递给“ 22”以使用它。
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 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\",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();
    ,正如其他人指出的那样,实现\'com.google.android.material:material:1.0.0 \'更简单 有关更多信息,请参阅此材料指南。 https://material.io/develop/android/docs/getting-started/
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();
    ,尝试这个。
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();
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-