AlertDialog's items not displayed
AndroidAndroid AlertdialogAndroid Problem Overview
I create an AlertDialog
with an AlertDialog.Builder
and set some items with setItems()
. The dialog is shown but I cannot see any of the items. All I see is the message.
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setMessage("Pick a color");
dialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do anything you want here
}
});
dialogBuilder.create().show();
If I set the PositiveButton
, I can see that button just fine. I also tried setting MultiChoiceItems
and SingleChoiceItems
but neither of these work either.
Android Solutions
Solution 1 - Android
Use setTitle
instead of setMessage
which sets message body and overrides the items list.
Solution 2 - Android
Why don't you go for setTitle
instead of the setMessage
? Try with setTitle("Pick a color")
.
I hope it will help you.
Solution 3 - Android
If you want to set a message AND items, just use setCustomTitle()
with a TextView
like so:
dialogBuilder.setCustomTitle(TextView(context).apply {
setPadding(
16.dpToPx().toInt(),
16.dpToPx().toInt(),
16.dpToPx().toInt(),
0
)
setText(it.message)
setTextColor(Color.BLACK)
textSize = 18f
})
dialogBuilder.setItems(...)
Note, that you cannot set a title this way, but of course you could create a custom title layout which support setting both the title AND the message.
dpToPx()
is just a simple conversion extension function and not in the scope of your question, but here it is for completeness sake:
@JvmOverloads
@Dimension(unit = Dimension.PX)
fun Number.dpToPx(
metrics: DisplayMetrics = Resources.getSystem().displayMetrics
): Float {
return toFloat() * metrics.density
}
Solution 4 - Android
Try alertDialogBuilder.setCustomTitle(view)
Solution 5 - Android
Use Below Code:-
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setTitle("Pick a color");
dialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do anything you want here
}
});
dialogBuilder.create().show();
Solution 6 - Android
try this
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setTitle("Pick a color");
dialogBuilder.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
dialogBuilder.show();
Solution 7 - Android
If you are using a resource string array you must include the resource packaging. context().getResources().getStringArray(R.array.items);
My list was not showing by using the R.array.items until i gave the pointer the context and resource packaging.
Good luck!