如何在Android警告对话框中显示列表视图?

时间:2021-07-18 07:21:53

In an Android application, I want to display a custom list view in an AlertDialog.

在Android应用程序中,我想在AlertDialog中显示一个自定义列表视图。

How can I do this?

我该怎么做呢?

8 个解决方案

#1


415  

Used below code to display custom list in AlertDialog

使用下面的代码在AlertDialog中显示自定义列表

AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");

builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
                builderInner.setMessage(strName);
                builderInner.setTitle("Your Selected Item is");
                builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,int which) {
                                dialog.dismiss();
                            }
                        });
                builderInner.show();
            }
        });
builderSingle.show();

#2


114  

You can use a custom dialog.

您可以使用自定义对话框。

Custom dialog layout. list.xml

自定义对话框的布局。list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ListView
        android:id="@+id/lv"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"/>
</LinearLayout>

In your activity

在你的活动

Dialog dialog = new Dialog(Activity.this);
       dialog.setContentView(R.layout.list)

ListView lv = (ListView ) dialog.findViewById(R.id.lv);
dialog.setCancelable(true);
dialog.setTitle("ListView");
dialog.show();

Edit:

编辑:

Using alertdialog

使用alertdialog

String names[] ={"A","B","C","D"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();

custom.xml

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

</ListView>

Snap

提前

如何在Android警告对话框中显示列表视图?

#3


95  

According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

根据文件,有三种列表可以用于AlertDialog:

  1. Traditional single-choice list
  2. 传统的单一选择列表
  3. Persistent single-choice list (radio buttons)
  4. 持久性单选列表(单选按钮)
  5. Persistent multiple-choice list (checkboxes)
  6. 持续的多项选择题列表(复选框)

I will give an example of each below.

下面我将给出每个例子。

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

制作传统的单选择列表的方法是使用setItems。

如何在Android警告对话框中显示列表视图?

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat
        }
    }
});

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

不需要使用OK按钮,因为只要用户单击列表项控件就会返回给OnClickListener。

Radio button list

如何在Android警告对话框中显示列表视图?

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

与传统列表相比,单选按钮列表的优点是用户可以看到当前的设置。创建单选按钮列表的方法是使用setSingleChoiceItems。

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user checked an item
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

我在这里硬编码了所选择的项,但是您可以使用实际项目中的类成员变量来跟踪它。

Checkbox list

如何在Android警告对话框中显示列表视图?

The way to make a checkbox list is to use setMultiChoiceItems.

创建复选框列表的方法是使用setMultiChoiceItems。

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");

// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        // user checked or unchecked a box
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

这里我硬编码了列表中哪些项已经被选中。您更可能希望在ArrayList 中跟踪它们。有关更多细节,请参见文档示例。如果您总是希望所有内容都开始未检查,也可以将选中的项设置为null。

Notes

  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • 对于上面代码中的上下文,不要使用getApplicationContext(),否则您将获得一个IllegalStateException(参见这里的原因)。相反,获取对活动上下文的引用,比如这个。
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • 您还可以使用setAdapter或setCursor或将游标或ListAdapter传入setSingleChoiceItems或setMultiChoiceItems,从数据库或其他源中填充列表项。
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • 如果列表比屏幕上显示的要长,那么对话框会自动滚动列表。如果你有一个很长的列表,我猜你应该用一个回收视图做一个自定义对话框。
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    为了测试上面所有的例子,我有一个简单的项目,只有一个按钮,比点击时显示的对话框要简单:

    import android.support.v7.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        Context context;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context = this;
        }
    
        public void showAlertDialogButtonClicked(View view) {
    
            // example code to create alert dialog lists goes here
        }
    }
    

Related

#4


38  

final CharSequence[] items = {"A", "B", "C"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        // Do something with the selection
        mDoneButton.setText(items[item]);
    }
});
AlertDialog alert = builder.create();
alert.show();

#5


10  

Use the "import android.app.AlertDialog;" import and then you write

使用“import android.app.AlertDialog”导入,然后写入。

    String[] items = {"...","...."};             
    AlertDialog.Builder build = new AlertDialog.Builder(context);
    build.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //do stuff....
        }
    }).create().show();

#6


3  

As a beginner I would suggest you go through http://www.mkyong.com/android/android-custom-dialog-example/

作为一个初学者,我建议你浏览http://www.mkyong.com/android/android- - -example/。

I'll rundown what it basically does

我将简略说明它的基本功能

  1. Creates an XML file for the dialog and main Activity
  2. 为对话框和主活动创建一个XML文件
  3. In the main activity in the required place creates an object of android class Dialog
  4. 在所需位置的主要活动中创建了一个android类对话框的对象。
  5. Adds custom styling and text based on the XML file
  6. 根据XML文件添加自定义样式和文本
  7. Calls the dialog.show() method.
  8. 调用dialog.show()方法。

#7


2  

This is too simple

这是太简单了

final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};

AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);

builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (items[item].equals("Take Photo")) {
            getCapturesProfilePicFromCamera();
        } else if (items[item].equals("Choose from Library")) {
            getProfilePicFromGallery();
        } else if (items[item].equals("Cancel")) {
            dialog.dismiss();
        }
    }
});
builder.show();

#8


0  

Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?

在AlertDialog中创建EditText单元后调用一个方法,以供通用使用,这不是更容易吗?

public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
    EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(SelectTitle);
            builder.setItems(SelectList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int item) {
                    EditTextItem.setText(SelectList[item]);
                }
            });
            builder.create().show();
            return false;
        }
    });
}

#1


415  

Used below code to display custom list in AlertDialog

使用下面的代码在AlertDialog中显示自定义列表

AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");

builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
                builderInner.setMessage(strName);
                builderInner.setTitle("Your Selected Item is");
                builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,int which) {
                                dialog.dismiss();
                            }
                        });
                builderInner.show();
            }
        });
builderSingle.show();

#2


114  

You can use a custom dialog.

您可以使用自定义对话框。

Custom dialog layout. list.xml

自定义对话框的布局。list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ListView
        android:id="@+id/lv"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"/>
</LinearLayout>

In your activity

在你的活动

Dialog dialog = new Dialog(Activity.this);
       dialog.setContentView(R.layout.list)

ListView lv = (ListView ) dialog.findViewById(R.id.lv);
dialog.setCancelable(true);
dialog.setTitle("ListView");
dialog.show();

Edit:

编辑:

Using alertdialog

使用alertdialog

String names[] ={"A","B","C","D"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();

custom.xml

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

</ListView>

Snap

提前

如何在Android警告对话框中显示列表视图?

#3


95  

According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

根据文件,有三种列表可以用于AlertDialog:

  1. Traditional single-choice list
  2. 传统的单一选择列表
  3. Persistent single-choice list (radio buttons)
  4. 持久性单选列表(单选按钮)
  5. Persistent multiple-choice list (checkboxes)
  6. 持续的多项选择题列表(复选框)

I will give an example of each below.

下面我将给出每个例子。

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

制作传统的单选择列表的方法是使用setItems。

如何在Android警告对话框中显示列表视图?

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat
        }
    }
});

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

不需要使用OK按钮,因为只要用户单击列表项控件就会返回给OnClickListener。

Radio button list

如何在Android警告对话框中显示列表视图?

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

与传统列表相比,单选按钮列表的优点是用户可以看到当前的设置。创建单选按钮列表的方法是使用setSingleChoiceItems。

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user checked an item
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

我在这里硬编码了所选择的项,但是您可以使用实际项目中的类成员变量来跟踪它。

Checkbox list

如何在Android警告对话框中显示列表视图?

The way to make a checkbox list is to use setMultiChoiceItems.

创建复选框列表的方法是使用setMultiChoiceItems。

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");

// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        // user checked or unchecked a box
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

这里我硬编码了列表中哪些项已经被选中。您更可能希望在ArrayList 中跟踪它们。有关更多细节,请参见文档示例。如果您总是希望所有内容都开始未检查,也可以将选中的项设置为null。

Notes

  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • 对于上面代码中的上下文,不要使用getApplicationContext(),否则您将获得一个IllegalStateException(参见这里的原因)。相反,获取对活动上下文的引用,比如这个。
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • 您还可以使用setAdapter或setCursor或将游标或ListAdapter传入setSingleChoiceItems或setMultiChoiceItems,从数据库或其他源中填充列表项。
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • 如果列表比屏幕上显示的要长,那么对话框会自动滚动列表。如果你有一个很长的列表,我猜你应该用一个回收视图做一个自定义对话框。
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    为了测试上面所有的例子,我有一个简单的项目,只有一个按钮,比点击时显示的对话框要简单:

    import android.support.v7.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        Context context;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context = this;
        }
    
        public void showAlertDialogButtonClicked(View view) {
    
            // example code to create alert dialog lists goes here
        }
    }
    

Related

#4


38  

final CharSequence[] items = {"A", "B", "C"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        // Do something with the selection
        mDoneButton.setText(items[item]);
    }
});
AlertDialog alert = builder.create();
alert.show();

#5


10  

Use the "import android.app.AlertDialog;" import and then you write

使用“import android.app.AlertDialog”导入,然后写入。

    String[] items = {"...","...."};             
    AlertDialog.Builder build = new AlertDialog.Builder(context);
    build.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //do stuff....
        }
    }).create().show();

#6


3  

As a beginner I would suggest you go through http://www.mkyong.com/android/android-custom-dialog-example/

作为一个初学者,我建议你浏览http://www.mkyong.com/android/android- - -example/。

I'll rundown what it basically does

我将简略说明它的基本功能

  1. Creates an XML file for the dialog and main Activity
  2. 为对话框和主活动创建一个XML文件
  3. In the main activity in the required place creates an object of android class Dialog
  4. 在所需位置的主要活动中创建了一个android类对话框的对象。
  5. Adds custom styling and text based on the XML file
  6. 根据XML文件添加自定义样式和文本
  7. Calls the dialog.show() method.
  8. 调用dialog.show()方法。

#7


2  

This is too simple

这是太简单了

final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};

AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);

builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (items[item].equals("Take Photo")) {
            getCapturesProfilePicFromCamera();
        } else if (items[item].equals("Choose from Library")) {
            getProfilePicFromGallery();
        } else if (items[item].equals("Cancel")) {
            dialog.dismiss();
        }
    }
});
builder.show();

#8


0  

Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?

在AlertDialog中创建EditText单元后调用一个方法,以供通用使用,这不是更容易吗?

public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
    EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(SelectTitle);
            builder.setItems(SelectList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int item) {
                    EditTextItem.setText(SelectList[item]);
                }
            });
            builder.create().show();
            return false;
        }
    });
}