在一个Android应用程序中,我想在AlertDialog中显示一个自定义列表视图。
我该怎么做呢?
在一个Android应用程序中,我想在AlertDialog中显示一个自定义列表视图。
我该怎么做呢?
当前回答
您可以使用自定义对话框。
自定义对话框布局。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>
在你的活动中
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();
编辑:
使用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.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();
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
其他回答
您可以使用自定义对话框。
自定义对话框布局。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>
在你的活动中
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();
编辑:
使用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.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();
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
这太简单了
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();
根据文档,AlertDialog可以使用三种类型的列表:
传统单选列表 持久的单选列表(单选按钮) 持久的多项选择列表(复选框)
下面我将分别给出一个例子。
传统单选列表
制作传统单选列表的方法是使用setItems。
Java版本
// 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();
不需要OK按钮,因为只要用户单击列表项控件,就会返回到OnClickListener。
芬兰湾的科特林版本
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")
// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
when (which) {
0 -> { /* horse */ }
1 -> { /* cow */ }
2 -> { /* camel */ }
3 -> { /* sheep */ }
4 -> { /* goat */ }
}
}
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
单选按钮列表
单选按钮列表相对于传统列表的优点是用户可以看到当前设置是什么。创建单选按钮列表的方法是使用setSingleChoiceItems。
Java版本
// 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();
我在这里硬编码了选定的项,但您可以在实际项目中使用类成员变量跟踪它。
芬兰湾的科特林版本
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")
// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
// user checked an item
}
// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// user clicked OK
}
builder.setNegativeButton("Cancel", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
复选框列表
创建复选框列表的方法是使用setMultiChoiceItems。
Java版本
// 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();
在这里,我硬编码了列表中已经检查的项目。更可能的情况是,您希望在ArrayList<Integer>中跟踪它们。有关详细信息,请参阅文档示例。如果您总是希望所有内容都开始时未选中,还可以将选中的项目设置为null。
芬兰湾的科特林版本
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")
// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
// user checked or unchecked a box
}
// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// user clicked OK
}
builder.setNegativeButton("Cancel", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
笔记
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. 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. 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 } }
相关的
Android警报对话框有一个,两个和三个按钮 如何实现自定义AlertDialog视图
private void AlertDialogue(final List<Animals> animals) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AdminActivity.this);
alertDialog.setTitle("Filter by tag");
final String[] animalsArray = new String[animals.size()];
for (int i = 0; i < tags.size(); i++) {
animalsArray[i] = tags.get(i).getanimal();
}
final int checkedItem = 0;
alertDialog.setSingleChoiceItems(animalsArray, checkedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "onClick: " + animalsArray[which]);
}
});
AlertDialog alert = alertDialog.create();
alert.setCanceledOnTouchOutside(false);
alert.show();
}
这是如何显示自定义布局对话框与自定义列表项,可以根据您的要求自定义。
步骤- 1创建对话框的布局
R.layout.assignment_dialog_list_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rectangle_round_corner_assignment_alert"
android:orientation="vertical">
<TextView
android:id="@+id/tv_popup_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:singleLine="true"
android:paddingStart="4dp"
android:text="View as:"
android:textColor="#4f4f4f" />
<ListView
android:id="@+id/lv_assignment_users"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
步骤- 2创建自定义列表项布局根据您的业务逻辑
R.layout.item_assignment_dialog_list_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="4dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_user_profile_image"
android:visibility="visible"
android:layout_width="42dp"
android:layout_height="42dp" />
<TextView
android:id="@+id/tv_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:layout_marginStart="8dp"
android:paddingBottom="8dp"
android:textColor="#666666"
android:textSize="18sp"
tools:text="ABCD XYZ" />
</LinearLayout>
步骤- 3创建一个你自己选择的数据模型类
public class AssignmentUserModel {
private String userId;
private String userName;
private String userRole;
private Bitmap userProfileBitmap;
public AssignmentUserModel(String userId, String userName, String userRole, Bitmap userProfileBitmap) {
this.userId = userId;
this.userName = userName;
this.userRole = userRole;
this.userProfileBitmap = userProfileBitmap;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public Bitmap getUserProfileBitmap() {
return userProfileBitmap;
}
public void setUserProfileBitmap(Bitmap userProfileBitmap) {
this.userProfileBitmap = userProfileBitmap;
}
}
步骤- 4创建自定义适配器
public class UserListAdapter extends ArrayAdapter<AssignmentUserModel> {
private final Context context;
private final List<AssignmentUserModel> userList;
public UserListAdapter(@NonNull Context context, int resource, @NonNull List<AssignmentUserModel> objects) {
super(context, resource, objects);
userList = objects;
this.context = context;
}
@SuppressLint("ViewHolder")
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_assignment_dialog_list_layout, parent, false);
ImageView profilePic = rowView.findViewById(R.id.iv_user_profile_image);
TextView userName = rowView.findViewById(R.id.tv_user_name);
AssignmentUserModel user = userList.get(position);
userName.setText(user.getUserName());
Bitmap bitmap = user.getUserProfileBitmap();
profilePic.setImageDrawable(bitmap);
return rowView;
}
}
步骤- 5创建这个函数,并在这个方法中提供上述数据模型的ArrayList
// Pass list of your model as arraylist
private void showCustomAlertDialogBoxForUserList(ArrayList<AssignmentUserModel> allUsersList) {
final Dialog dialog = new Dialog(mActivity);
dialog.setContentView(R.layout.assignment_dialog_list_view);
if (dialog.getWindow() != null) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // this is optional
}
ListView listView = dialog.findViewById(R.id.lv_assignment_users);
TextView tv = dialog.findViewById(R.id.tv_popup_title);
ArrayAdapter arrayAdapter = new UserListAdapter(context, R.layout.item_assignment_dialog_list_layout, allUsersList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener((adapterView, view, which, l) -> {
Log.d(TAG, "showAssignmentsList: " + allUsersList.get(which).getUserId());
// TODO : Listen to click callbacks at the position
});
dialog.show();
}
步骤- 6给对话框圆角背景
@drawable / rectangle_round_corner_assignment_alert
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff" />
<corners android:radius="16dp" />
<padding
android:bottom="16dp"
android:left="16dp"
android:right="16dp"
android:top="16dp" />
</shape>