`

Android 对话框 (一) 管理对话框

阅读更多
转过来的贴,不想动原文,划分了原文的模块!添加了代码和效果。在此为勒些共享技术的程序员表示由衷的感谢和诚挚的问候!
原帖:http://hi.baidu.com/leran0222/blog/item/b5395a4b908628fa83025c7e.html

(原文)

/**
用户可以继承Dialog类或者它的子类并且创建一个新的layout。

Showing a Dialog

Dialog总是作为一个Activity的一部分来创建和显示的。正常可以使用Activity的onCreateDialog(int)回调函数来创建Dialog。使用这个回调函数的时候,系统会自动管理每个dialog的状态,并把它们关联到这个Activity,有效的使它成为dialog的所有者。这样每个第啊咯个都从父Activity继承一些属性。For example, when a dialog is open, the Menu key reveals the options menu defined for the Activity and the volume keys modify the audio stream used by the Activity.
注意:如果你在onCreate()之外创建dialog,他不会附属于任何的Activity,可以使用dialog的setOwnerActivity(Activity)来设置。
当想显示一个dialog的时候,调用showDialog(int),并传递一个整数来唯一标识想要显示的dialog即可。
当第一次使用一个dialog的时候,Android会调用onCreateDialog(int),应该在这里创建dialog。这个回调方法的参数是你传递给showDialog(int)的id。创建Dialog结束后,返回这个dialog对象。
在现实一个dialog之前,Android会先用可选的回调非法onPrepareDialog(int)。如果想在每次打开dialog的时候改变它的属性就可以通过重写这个方法来实现。他会在每次打开dialog的时候被调用,而onCreateDialog(int)只在第一次打开一个dialog的时候调用。如果不定义onPrepareDialog(),那么dialog将保持塌方上次被打开的属性。This method is also passed the dialog's ID, along with the Dialog object you created in onCreateDialog()。

创建Dialog的Example:
static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case DIALOG_PAUSED_ID:
// do the work to define the pause Dialog
break;
case DIALOG_GAMEOVER_ID:
// do the work to define the game over Dialog
break;
default:
dialog = null;
}
return dialog;
}

显示创建的dialog:showDialog(DIALOG_PAUSED_ID);
**/


/**
这里我贴一段代码,一切尽在代码中:

public class DialogAppActivity extends Activity implements android.view.View.OnClickListener{
	
	private Button btn1,btn2,btn3,dialogbtn;
	private Context context;
	private Integer DIALOG_ID;
	private Boolean DIALOG_IS_OPEN = false;
	AlertDialog dialog = null;
	AlertDialog.Builder builder = null;
	View dialogview = null;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = this;
        dialogview = getView();
        init();
    }
    
    public void init(){
    	btn1 = (Button) findViewById(R.id.btn1);
    	btn2 = (Button) findViewById(R.id.btn2);
    	btn3 = (Button) findViewById(R.id.btn3);
    	dialogbtn = (Button) dialogview.findViewById(R.id.dialogbtn);
    	btn1.setOnClickListener(this);
    	btn2.setOnClickListener(this);
    	btn3.setOnClickListener(this);
    	dialogbtn.setOnClickListener(this);
    	
    	builder = new AlertDialog.Builder(context);
		builder.setView(dialogview);
		dialog = builder.create();
    }

	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.btn1:
			DIALOG_ID = 1;
			break;
		case R.id.btn2:
			DIALOG_ID = 2;
			break;
		case R.id.btn3:
			DIALOG_ID = 3;
			break;
		case R.id.dialogbtn:
            //把 removeDialog(DIALOG_ID)改为dismissDialog(DIALOG_ID)
            //或者dialog.cancle,dialog.dismiss,看完效果就懂下文介绍dismiss的内容
			removeDialog(DIALOG_ID);
			break;
		}
		if(arg0.getId()!=R.id.dialogbtn){
			dialogbtn.setText("Click DIALOG_ID :"+String.valueOf(DIALOG_ID));
			showDialog(DIALOG_ID);
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case 1:
			dialog.setTitle("Demo one");
			dialog.setMessage("第一个Dialog");
			break;
		case 2:
			dialog.setTitle("Demo two");
			dialog.setMessage("第二个Dialog");
			break;
		case 3:
			dialog.setTitle("Demo three");
			dialog.setMessage("第三个Dialog");
			break;
		default:
			break;
		}
		return dialog;
	}
	
	public View getView(){
		return LayoutInflater.from(DialogAppActivity.this).inflate(R.layout.dialog_layout, null);
	}
}



//dialog_layout.xml布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
	android:id="@+id/dialogbtn"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
/>
</LinearLayout>

//main.xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
	android:id="@+id/btn1"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="Demo1"
/>
<Button
	android:id="@+id/btn2"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="Demo2"
/>
<Button
	android:id="@+id/btn3"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="Demo3"
/>
</LinearLayout>


**/


Dismissing a Dialog

当准备关闭dialog的时候,可以调用dialogobject的dismiss()方法。如果必要,可以调用Activity的dismissDialog(int),它会有效的调用dialog的dismiss()。
如果你使用onCreateDialog(int)来管理dialog的状态,那么每次关闭dialog的时候,dialog的状态都会被Activity保存。如果这个dialog不会再次被使用或者清除它的状态很重要,可以调用removeDialog(int),这回清除内部任何对它的引用,如果它正在显示,会被关闭。

Using dismiss listeners

如果想在dialog被关闭的时候执行一些操作,应该为dialog设置on-dismiss listener。

首先定义DialogInterfacev.OnDismissListener接口。这个接口只有一个方法,vonDismiss(DialogInterface),当关闭dialog的时候会调用这个方法。把OnDismissListener的实现传递给setOnDismissListener()就可以了。
注意,dialog可以被取消。这是由用户显示取消dialog的特殊情况,在用户点击back键或者显示调用cancel()函数就是这种情况。当dialog被cancel的时候,OnDismissListener不会被通知,如果你想知道dialog被显示的cancel(不是正常的关闭),那么你应该用setOnCancel()注册一个vDialogInterface.OnCancelListener。

Creating an AlertDialog
AlertDialog是Dialog的子类,它可以构造用户交互的多数dialog,是建议的dialog类型。下列情况可以使用AldertDialog:
A tittle;
A text message;
One,two,or three buttons;
A list of selectable items (with optional checkboxes or radio buttons)

可以使用AlertDialog.Builder的子类来创建AlertDialog。通过AlertDialogBuilder(Context)来创建一个builder并使用这个builder的public方法来定义AlertDialog的所有属性。在使用builder创建结束后,使用create()来得到创建的AlertDialog对象。

The following topics show how to define various properties of the AlertDialog using the AlertDialog.Builder class. If you use any of the following sample code inside your onCreateDialog() callback method, you can return the resulting Dialog object to display the dialog.

Adding buttons
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();

注意:每种类型的按钮只能添加一个。这限制了按钮的个数(3个)。这些名字于其功能无关只用来帮助你记住这些按钮是干嘛的。

Adding a list

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();

Adding checkboxes and radio buttons

可以用vsetMultiChoiceitems()和setSingleChoiceItems()来在AlertDialog上设置多选或者单选列表。如果使用onCreateDialog()创建这些选项列表,那么Android会维护这个选项列表的状态。在Activity存活期间,这个dialog会记住先前的选项状态,但是当用户利卡这个Activity时,选项状态就会丢失。
注意:为了在用户退出或者暂停这个Activity时保存选项状态,你必须在整个Activity的生命周期中恰当的保存和恢复选项状态。为了永久的保存选项状态(甚至在Activity进程完全结束之后),你应该使用数据存储技术来保存选项状态。

To create an AlertDialog with a list of single-choice items like the one shown to the right, use the same code from the previous example, but replace the setItems() method with setSingleChoiceItems():

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();

在setSingleChoiceItems()的第二个参数是一个整形表示哪个item被选中,item的标识从0开始,-1表示没有item默认被选中。
自己做的一些案例,供参考:
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics