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

前端之家收集整理的这篇文章主要介绍了android – AlertDialog – 不要关闭项目点击前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好,所以我正在创建一个ArrayAdapter并在我的Alert Dialog中使用它,因为我不想在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

解决方法

>您可以将自定义ListView设置为AlertDialog的内容并设置OnItemClickListener
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String[] items = ...;
ListView list = new ListView(this);
list.setAdapter(new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,items));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0,View view,int pos,long id) {
            ...
        }
    });
builder.setView(list);

然后保存对话框的引用

mDialog = builder.show();

以便在必要时解散

mDialog.dismiss();

猜你在找的Android相关文章