AlertDialog
creates its content dynamically by checking if mMessage
that you set via setMessage()
is null
. If mMessage
is NOT null
(that means you have called setMessage()
method), then it setups its content for ONLY TextView
to show message and skips listview
setup. If you haven't called setMessage()
, then it removes TextView
and then setups for listview
.
Solution
So, to show both message and list in dialog, I suggest you to use below solution which setups custom view for AlertDialog.
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Dialog title");
final List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
final ArrayAdapter<String> arrayAdapterItems = new ArrayAdapter<String>(
getContext(), android.R.layout.simple_list_item_single_choice, items);
View content = getLayoutInflater().inflate(R.layout.list_msg_dialog, null);
//this is the TextView that displays your message
TextView tvMessage = content.findViewById(R.id.tv_msg);
tvMessage.setText("Dialog message!!!");
//this is the ListView that lists your items
final ListView lvItems = content.findViewById(R.id.lv_items);
lvItems.setAdapter(arrayAdapterItems);
lvItems.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
builder.setView(content);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do something
Toast.makeText(MainActivity.this,
items.get(lvItems.getCheckedItemPosition()),
Toast.LENGTH_SHORT).show();
}
});
final AlertDialog dialog = builder.create();
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//when you need to act on itemClick
}
});
dialog.show();
And this is list_msg_dialog.xml
layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="3dp">
<TextView
android:id="@+id/tv_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="15dp"
android:text="some text"
android:textAppearance="?android:attr/textAppearanceListItem"
android:textColor="@android:color/black"
android:textSize="18sp" />
<ListView
android:id="@+id/lv_items"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null" /></LinearLayout>