AlertDialog 使用 扩展
AlertDialog
?
?
[功能]
也是一种Dialog
?
?
[原理]
1. AlertDialog 本身并没有构造函数 即 不可以通过 new AlertDialog(...) 来初始化 而只能通过 AlertDialog.Builder
2. 而 AlertDialog.Builder 比较像是AlertDialog的构造器 用于接收各种和 AlertDialog 有关的参数 然后通过 create() 来创建目标 AlertDialog
?
[代码 步骤]
1. 定义 AlertDialog.Builder 实例 并接受一些参数 如:图片 标题 正文
ab = new AlertDialog.Builder(this);
?
ab.setTitle("HelloAlert").setMessage("Warning: its Alert Demo!").setIcon(R.drawable.robot);?
?
?2. 根据AlertDialog.Builder 创建 相应的 AlertDialog
aDialog = ab.create();
?
?
3. 弹出 AlertDialog
findViewById(R.id.button).setOnClickListener(new OnClickListener(){public void onClick(View v) {// TODO Auto-generated method stubaDialog.show();} });?
?
4. 取消 AlertDialog
aDialog.setOnKeyListener(new OnKeyListener(){@Overridepublic boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {// TODO Auto-generated method stubaDialog.dismiss();return true;} });?
?
?* emulator 运行截图:
?
?
?
?
5. 以上所采用的都是AlertDialog 系统默认的布局 现在说自定义布局的情况 并添加一个用于取消AlertDialog 的 Button
?
* 定义其布局 hello.main
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" ><ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/robot" /><LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" ><TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HelloAlert!" /><TextView android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="10dip" /> </LinearLayout></LinearLayout>
?
?
* 通过LayoutInflater 得到上面 hello.xml 布局的 View view
view = this.getLayoutInflater().inflate(R.layout.hello, null);
?
* 指定AlertDialog.Builder 所需的布局 并返回目标AlertDialog
ab.setView(view);aDialog = ab.create();
?
* 通过 view.findViewById() 得到 目标View 然后设置其内容 如:
TextView title = (TextView) view.findViewById(R.id.title); title.setTextSize(20); title.setTextColor(Color.RED); title.setText("HelloAlert"); TextView message = (TextView) view.findViewById(R.id.message); message.setText("Warning: it's Alert Demo!");?
?
* 弹出 AlertDialog
findViewById(R.id.button).setOnClickListener(new OnClickListener(){public void onClick(View v) {// TODO Auto-generated method stubaDialog.show();} });?
* 取消 AlertDialog
view.setOnClickListener(new OnClickListener(){public void onClick(View v) {// TODO Auto-generated method stubaDialog.dismiss();} });?
?* emulator 运行截图:
?