Create List in Alert Dialog Popup in Android
Android Alert Dialog provides lots of option for customization. Such as we can create Confirm Dialog, Action Dialog, Custom View or Form in Dialog, List Selection in Alert Dialog.
Here we will know about list selection in Android Alert Dialog.
Step 1: Create a global variable for the list and assign options on creating.
public class MainActivity extends AppCompatActivity {
String[] options;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = {"Option 1","Option 2","Option 3","Option 4"};
}
}
Step 2: Create an event listener button by which Dialog will open. Then create Alert Dialog.
public class MainActivity extends AppCompatActivity {
String[] options;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = {"Option 1","Option 2","Option 3","Option 4"};
View btn = findViewById(R.id.btnOpenDialog);
btn.setClickable(true);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select Option");
builder.setItems(options, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(SettingsActivity.this, options[item], Toast.LENGTH_LONG);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Keywords: