单击“获取警报”对话框项列表以显示在其他片段,适配器或活动中

时间:2018-10-26 00:32:42

标签: java android alertdialog android-alertdialog

我对如何实现此目标一无所知,我列出了芒果,香蕉,菠萝等一般(水果)等项目的清单,一旦单击我的设置中的“选择水果”部分,我就会使用警报对话框显示它们活动。

我现在的问题是,一旦在不同的地方(例如,在类,片段和适配器上)选择了这些水果,我就想知道如何才能获得被单击的项目并将其设置在我拥有的不同textviews中项目,并且从事不同的活动。

我的简单对话框示例

 final String[] items = {"Apple", "Banana", "Orange", "Grapes","Mango","pawpaw", "ovacado", "peach", "pears",};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("List of Items")

                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), items[which] + " is clicked", Toast.LENGTH_SHORT).show();
                    }
                });
        builder.setPositiveButton("OK", null);
        builder.setNegativeButton("CANCEL", null);
        AlertDialog alertDialog = builder.create();

        alertDialog.show();

        Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
       button.setBackgroundColor(Color.GREEN);
        button.setTextColor(Color.WHITE);

一般想法,我应该能够获得所选项目并将其显示在我的适配器上。

holder1.fruitsTextView.setText( from the alert dialog selected item "mango" + fruitsDatas.get(position).getAllFruits());

此示例使用的图像。 That is my dialog which I want to pop up on my setting section, just an example of what I want to achieve

This is my Main activity text view where I want to display the selected item from the dialog

1 个答案:

答案 0 :(得分:0)

  private fun showAlertWithChoiceOption() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Choose an Option")

        val picker = arrayOf("Camera", "File Explorer", "Cancel")
        builder.setItems(picker) { dialog, which ->
            when (which) {
                0 -> {
                   //Camera Choosen 
    dialog.cancel()}
                1 -> {
                    //File Explorer Choosen  
    dialog.cancel()              }
                2 -> {
//Cancel Choosen
                    dialog.cancel()
                }
            }
        }

        val dialog = builder.create()
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

尝试上面的代码。它在Kotlin中