AlertDialog更改标题颜色,字体等

更改AlertDialog标题的方法google目前没有提供,只能通过其他办法

一种办法是:首先在源代码中找到有个叫AlertController的类,这个类就是AlertDialog的实现类,是没有对外公开的,然后在这个类中有个私有成员变量叫mTitleView,这个就是AlertDialog的title的TextView,所以只要得到这个成员变量的实例,即可自定义AlertDialog的title

得到这个的实例变量的方法通过两步反射来实现,如下:

  1. AlertDialog dialog = (AlertDialog) getDialog();  
  2. try {  
  3.     Field mAlert = AlertDialog.class.getDeclaredField("mAlert");  
  4.     mAlert.setAccessible(true);  
  5.     Object alertController = mAlert.get(dialog);  
  6.   
  7.     Field mTitleView = alertController.getClass().getDeclaredField("mTitleView");  
  8.     mTitleView.setAccessible(true);  
  9.   
  10.     TextView title = (TextView) mTitleView.get(alertController);  
  11.     title.setTextColor(0xff33b5e5);   
  12.   
  13. catch (NoSuchFieldException e) {  
  14.     e.printStackTrace();  
  15. catch (IllegalArgumentException e) {  
  16.     e.printStackTrace();  
  17. catch (IllegalAccessException e) {  
  18.     e.printStackTrace();  
  19. }  
  1. AlertDialog dialog = (AlertDialog) getDialog();  
  2. try {  
  3.     Field mAlert = AlertDialog.class.getDeclaredField("mAlert");  
  4.     mAlert.setAccessible(true);  
  5.     Object alertController = mAlert.get(dialog);  
  6.   
  7.     Field mTitleView = alertController.getClass().getDeclaredField("mTitleView");  
  8.     mTitleView.setAccessible(true);  
  9.   
  10.     TextView title = (TextView) mTitleView.get(alertController);  
  11.     title.setTextColor(0xff33b5e5);   
  12.   
  13. catch (NoSuchFieldException e) {  
  14.     e.printStackTrace();  
  15. catch (IllegalArgumentException e) {  
  16.     e.printStackTrace();  
  17. catch (IllegalAccessException e) {  
  18.     e.printStackTrace();  
  19. }  

当然还有其他办法,比如直接把title隐藏掉,然后在content View中自定义一个title出来等等

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值