您经常需要显示一个对话框窗口,以便从用户那里得到确认。这时,可以重写在Activity基类中定义的受保护的onCreateDialog()方法来显示一个对话框窗口。
package com.example.androidtest; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.Toast; public class DialogActivity extends Activity implements OnClickListener { CharSequence[] items = {"Google", "Apple", "Microsoft"}; boolean[] itemsChecked = new boolean[items.length]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); Button btn = (Button)this.findViewById(R.id.button1); btn.setOnClickListener(this); } public void onClick(View v) { showDialog(0); } @Override protected Dialog onCreateDialog(int id) { switch(id) { case 0: Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("title"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //这里要用getBaseContext()来获取DialogActivity的上下文对象。 Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show(); } }); builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getBaseContext(), items[which] + (isChecked ? " checked!" : " unchecked!"), Toast.LENGTH_SHORT).show(); } }); return builder.create(); } return null; } }
运行效果