对话框
通过builder来构建一个单选框
package xidian.dy.com.chujia; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); if(btn != null) btn.setOnClickListener(new MyLister()); } class MyLister implements View.OnClickListener{ @Override public void onClick(View v) { //通过内部类Build来构建一个对话框 AlertDialog.Builder builer = new AlertDialog.Builder(MainActivity.this); builer.setIcon(android.R.drawable.alert_dark_frame); //设置对话框的标题 builer.setTitle("请选择性别"); //设置单选框内容 String[] items = new String[]{"男", "女"}; builer.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == 0) Toast.makeText(MainActivity.this, "男被选中", Toast.LENGTH_SHORT).show(); else Toast.makeText(MainActivity.this, "女被选中", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); builer.show(); } } }
复选框
package xidian.dy.com.chujia; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); if(btn != null) btn.setOnClickListener(new MyLister()); } class MyLister implements View.OnClickListener{ @Override public void onClick(View v) { //通过内部类Build来构建一个对话框 AlertDialog.Builder builer = new AlertDialog.Builder(MainActivity.this); builer.setIcon(android.R.drawable.alert_dark_frame); //设置对话框的标题 builer.setTitle("请选择性别"); //设置单选框内容 String[] items = new String[]{"数学", "英语", "物理", "化学"}; final boolean[] checkItems = new boolean[]{false, false, false, false}; builer.setMultiChoiceItems(items, checkItems, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { checkItems[which] = isChecked; } }); builer.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builer.show(); } } }