Android进阶之AlertDialog自定义

来源:互联网 发布:保温杯推荐 知乎 编辑:程序博客网 时间:2024/05/16 08:50


AlertDialog的自定义方式有很多种,这里介绍两种。

 

第一种是比较简单的,只自定义内容。

在AlertDialog使用详解中,非常详细的介绍了以下六种使用方法。

一、简单的AlertDialog(只显示一段简单的信息,比如about us)

二、带按钮的AlertDialog(显示提示信息,让用户操作,比如exit时的警告框)

三、类似ListView的AlertDialog(展示内容,比如某人的一些注册信息)

四、类似RadioButton的AlertDialog(让用户选择,单选)

五、类似CheckBox的AlertDialog(让用户多选)

六、自定义View的AlertDialog(当以上方式满足不了你的需求,就要自定义了)

\

最后的第六种也就是自定义内容的实现方式,比如想做一个这种登录对话框,通过前五种方式明显实现不了。

这时候就通过AlertDialog.Builder的setView把自己定义的登录界面设置进去,

而标题和按钮都还用Android原生的,如果你是像这种方式的自定义,请进前面链接查看最后一种方式。

 

这里介绍第二种方式。

先看一下效果,左图为原生的AlertDialog,右图为自定义的AlertDialog,这样自定义主要是为了让界面更加统一。

代码如下:

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. String info = cityData.getPointerList().get(position).toString();  
  2. AlertDialog alertDialog = new AlertDialog.Builder(CityActivity.this).create();  
  3. alertDialog.show();  
  4. Window window = alertDialog.getWindow();  
  5. window.setContentView(R.layout.dialog_main_info);  
  6. TextView tv_title = (TextView) window.findViewById(R.id.tv_dialog_title);  
  7. tv_title.setText("详细信息");  
  8. TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);  
  9. tv_message.setText(info);  

布局文件:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#ffff"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <TextView  
  9.         android:id="@+id/tv_dialog_title"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:background="#7a7"  
  13.         android:padding="8dp"  
  14.         android:textColor="#eee"  
  15.         android:textSize="20sp"  
  16.         android:textStyle="bold" />  
  17.   
  18.     <TextView  
  19.         android:id="@+id/tv_dialog_message"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_margin="5dp"  
  23.         android:padding="3dp" />  
  24.   
  25. </LinearLayout>  


其实这里自定义的主要目的就是想让title的背景颜色显示绿色,与activity的背景绿一致,比较和谐。

AlertDialog是Dialog的子类,也可以直接基于Dialog自定义。方法很多,用到了再尝试。


0 0