Search code examples
androidlistviewandroid-alertdialogcustomdialog

ListView items not displayed


I have a ListView in a custom dialog.

When I run the app, the view displays with correct number of lines for items in the array adapter.

However the lines displayed are blank.

I have tried setting the text color in the ListView to black to no avail.

    android:textColor="#000000"
    android:textSize="20sp"
    android:textStyle="bold"

If I add ten items to the view, then ten blank lines are displayed. I added a TextView to the layout and that displays correctly.

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listView">

</ListView>

</LinearLayout>

My code:

public class CustomDialog extends DialogFragment   {

private ArrayAdapter<String> adapter ;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = getActivity().getLayoutInflater();

    View dialogView =
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
        inflater.inflate(R.layout.custom_dialog, null);


    ArrayList<String> listItems = new ArrayList<>();

    listItems.add("test list item");

    adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, listItems);

    ListView listView = (ListView) dialogView.findViewById(R.id.listView);

    // Here, you set the data in your ListView
    listView.setAdapter(adapter);


    builder.setView(dialogView)
            // Add action buttons
            .setPositiveButton("Select", new ...                })
            .setNegativeButton("Cancel", new ...                });

    return builder.create();
}

Solution

  • Setting the textColor in the list view has no effect, you need to set it in the TextView from the layout which you pass to the adapter. Or you can change the background color of the dialog layout or the dialog theme.