转载请注明出处:【菜鸟的成长史http://blog.csdn.net/zjbpku/article/details/7836587】
最近对Dialog的使用比较频繁,在这个过程中发现经常用到的对话框也就几种,个人将其总结为以下几种:
样式一:
代码:
new AlertDialog.Builder(MainActivity.this) .setTitle("AlertDialog") // .setIcon(icon) .setMessage("text") .setPositiveButton("ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).setNegativeButton("cancel", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).show();
样式二:
代码:
final CharSequence[] items = { "Man", "Woman", "Boy", "Girl" }; new AlertDialog.Builder(MainActivity.this) .setTitle("Pick a item") .setItems(items, new OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }).show();
样式三:
代码:
final CharSequence[] items1 = { "Man", "Woman", "Boy", "Girl" }; new AlertDialog.Builder(MainActivity.this) .setTitle("Pick a item") .setSingleChoiceItems(items1, -1, new OnClickListener() { public void onClick(DialogInterface dialog, int position) { Toast.makeText( getApplicationContext(), position + "->" + items1[position], Toast.LENGTH_SHORT).show(); }).show();
样式四:
代码:
final CharSequence[] items2 = { "Man", "Woman", "Boy", "Girl" }; final boolean[] checked = { false, false, false, false }; new AlertDialog.Builder(MainActivity.this) .setTitle("Pick a item") .setMultiChoiceItems(items2, checked, new OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int position, boolean isChecked) { Toast.makeText( getApplicationContext(), items2[position] + "->" + isChecked, Toast.LENGTH_SHORT).show(); } }).show();
样式五:
xml:
命名为layout.xml,置于layout文件夹下
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="#ffffffff" android:orientation="horizontal" android:id="@+id/dialog"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/tvname" android:text="姓名:" /> <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/etname" android:minWidth="100dip"/></LinearLayout>
java代码:
LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.layout, null); AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity.this); builder.setTitle("自定义布局").setView(layout) .setPositiveButton("确定", null) .setNegativeButton("取消", null).show();
如果要获取EditView中的数据可在xml中定义id,然后 获取edit = (EditText)findViewById(id),通过getText()方法获取