閱讀619 返回首頁    go 阿裏雲 go 技術社區[雲棲]


AlertDialog更改標題顏色,字體等

更改AlertDialog標題的方法google目前沒有提供,隻能通過其他辦法

一種辦法是:首先在源代碼中找到有個叫AlertController的類,這個類就是AlertDialog的實現類,是沒有對外公開的,然後在這個類中有個私有成員變量叫mTitleView,這個就是AlertDialog的title的TextView,所以隻要得到這個成員變量的實例,即可自定義AlertDialog的title

得到這個的實例變量的方法通過兩步反射來實現,如下:

[java] view plaincopy
  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. }  
[java] view plaincopy
  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出來等等

最後更新:2017-04-03 12:56:21

  上一篇:go iOS上如何讓按鈕文本左對齊問題
  下一篇:go Android AlertDialog 獲取PositiveButton的控製權