android - AlertDialog - 不要关闭项目点击

标签 android android-alertdialog

好的,所以我正在创建一个 ArrayAdapter 并在我的警报对话框中使用它,因为我不想在 SingleItemSelection 对话框中显示默认单选按钮。

相反,我想更改所选项目的背景,然后当用户按下肯定按钮时,我将执行与所选项目相关的操作。

    private void showAlertDialog()
    {
        final String[] options = getResources().getStringArray(R.array.dialog_options);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, options);
        
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("My Dialog");
        
        dialogBuilder.setAdapter(adapter, new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "item clicked at index " + which, Toast.LENGTH_LONG).show();
// Here I need to change the background color of the item selected and prevent the dialog from being dismissed
            }
        });
    
        //String strOkay = getString(R.string.okay);
        dialogBuilder.setPositiveButton("OK", null); // TODO
        dialogBuilder.setNegativeButton("Cancel", null); // nothing simply dismiss
    
        AlertDialog dialog = dialogBuilder.create();
        dialog.show();
    }

我要解决两个问题。

How do I prevent the dialog from being dismissed when the user clicks on an item

How do I change the background of the item that has been selected when the user clicks on it

最佳答案

要防止在单击项目时关闭对话框,您可以使用 AdapterView.OnItemClickListener 而不是 DialogInterface.OnClickListener。

像这样:

dialogBuilder.setAdapter(adapter, null);
...
AlertDialog dialog = dialogBuilder.create();
alertDialog.getListView().setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do your stuff here
}
});

关于android - AlertDialog - 不要关闭项目点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20057944/

相关文章:

Android如何等到服务实际连接?

android - Android中没有互联网的语音识别

android - 有一种方法可以在 BottomSheetDialogFragment 中使用 AlertDialog 吗?

android - 在自定义警报对话框中获取单选按钮的值

android - 带有图像的 AlertDialog

java - 带有 SimpleAdapter 和单选模式的 AlertDialog 不显示单击的项目

android - 暂时禁用android中的互联网访问?

android - 为什么我应该在 Android 中手动关闭 AlertDialog?

android - 带倒计时器的警报对话框

android - Robolectric - BuildActivity(MyActivity.class).create() 抛出 NullPointerException