This code snippet shows an alert dialog that displays a list of choices.
The code is similar to what's used for the alert dialog that displays buttons (e.g. OK, Cancel).
This type of dialog takes the list item labels from a string array you need to create under res -> value.
String Array Example
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="Foods">
<item>Pizza</item>
<item>Cookies</item>
<item>Doughnuts</item>
<item>Soda</item>
<item>Lollipops</item>
<item>Ice Cream</item>
</string-array>
</resources>
Code Example
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AlertList extends Activity implements OnClickListener {
Button btn_Alert;
TextView tv_alert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert_list);
btn_Alert = (Button) findViewById(R.id.btn_Alert);
btn_Alert.setOnClickListener(this);
tv_alert = (TextView) findViewById(R.id.tv_Alert);
}
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(AlertList.this);
alert.setTitle("Select a food");
alert.setItems(R.array.Foods, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
Toast.makeText(AlertList.this, "You selected Pizza", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(AlertList.this, "You selected Cookies", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(AlertList.this, "You selected Doughnuts", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(AlertList.this, "You selected Soda", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(AlertList.this, "You selected Lollipops", Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(AlertList.this, "You selected Ice Cream", Toast.LENGTH_SHORT).show();
break;
}
}
});
alert.show();
};
}