Android进阶之AlertDialog自定义

前言

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

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

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

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

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

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

  4. 类似RadioButton的AlertDialog(让用户选择,单选)

  5. 类似CheckBox的AlertDialog(让用户多选)

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

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

源码

  这时候就通过AlertDialog.Builder的setView把自己定义的登录界面设置进去,而标题和按钮都还用Android原生的,如果你是像这种方式的自定义,即比如下面原样式显示的一般。

  这里介绍第二种自定义方式。

  先看一下效果,原样式(PS:仅仅标题栏部分是原样式)为原生的AlertDialog,自定义样式为自定义的AlertDialog,这样自定义主要是为了让界面更加统一。

原样式

这里写图片描述

自定义样式

这里写图片描述

源码

  核心方法是通过新建一个AlertDialog对象,通过获取AlertDialog对象所包含的Window这个成员变量来修改AlertDialog的样式。

    String info = cityData.getPointerList().get(position).toString(); 
    // 新建一个空白的AlertDialog对象,包括标题栏也是空白的
    AlertDialog alertDialog = new AlertDialog.Builder(CityActivity.this).create();  
    alertDialog.show();  
    // 获取AlertDialog对象的Window对象
    Window window = alertDialog.getWindow();  
    // 为当前Window对象设置自定义的样式
    window.setContentView(R.layout.dialog_main_info);  
    TextView tv_title = (TextView) window.findViewById(R.id.tv_dialog_title);  
    tv_title.setText("详细信息");  
    TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);  
    tv_message.setText(info);  

xml部分源码:

    <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:background="#ffff"  
        android:orientation="vertical" >  

        <TextView  
            android:id="@+id/tv_dialog_title"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:background="#7a7"  
            android:padding="8dp"  
            android:textColor="#eee"  
            android:textSize="20sp"  
            android:textStyle="bold" />  

        <TextView  
            android:id="@+id/tv_dialog_message"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_margin="5dp"  
            android:padding="3dp" />  

    </LinearLayout>  

  其实这里自定义的主要目的就是想让title的背景颜色显示绿色,与activity的背景绿一致,比较和谐。
  
  AlertDialog是Dialog的子类,也可以直接基于Dialog自定义。方法很多,用到了再尝试。

附录

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(转载请说明出处)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值