How to Display a ListView inside AlertDialog in Android?
In Android, A ListView is a ViewGroup that is used to display a list of strings. This view and scrollable and each item in a ListView is clickable. An Alert Dialog is a type of alert message that can be invoked to appear on the top of the screen. An Alert Dialog generally consists of a Title, a Message, a Positive, and a Negative Button. Users can choose between these two buttons to respond to the message. These two elements are quite different from each other in terms of implementation as well as the purposes served. However, it is possible to bring them together and display one inside the other.
So in this article, we will show you how you could create and display a ListView inside an Alert Dialog in Android. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Create a layout for ListView (row.xml)
Navigate to the app > res > layout and create a new layout file. Add a ListView as shown below. This layout would be displayed inside the AlertDialog.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Button as shown below. This Button on-click would generate an AlertDialog with a ListView inside it.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
You can see that when the button is clicked, the Alert Dialog is displayed with ListView inside it.
Please Login to comment...