AlertDialog更改標題顏色,字體等
更改AlertDialog標題的方法google目前沒有提供,隻能通過其他辦法
一種辦法是:首先在源代碼中找到有個叫AlertController的類,這個類就是AlertDialog的實現類,是沒有對外公開的,然後在這個類中有個私有成員變量叫mTitleView,這個就是AlertDialog的title的TextView,所以隻要得到這個成員變量的實例,即可自定義AlertDialog的title
得到這個的實例變量的方法通過兩步反射來實現,如下:
- AlertDialog dialog = (AlertDialog) getDialog();
- try {
- Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
- mAlert.setAccessible(true);
- Object alertController = mAlert.get(dialog);
- Field mTitleView = alertController.getClass().getDeclaredField("mTitleView");
- mTitleView.setAccessible(true);
- TextView title = (TextView) mTitleView.get(alertController);
- title.setTextColor(0xff33b5e5);
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- AlertDialog dialog = (AlertDialog) getDialog();
- try {
- Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
- mAlert.setAccessible(true);
- Object alertController = mAlert.get(dialog);
- Field mTitleView = alertController.getClass().getDeclaredField("mTitleView");
- mTitleView.setAccessible(true);
- TextView title = (TextView) mTitleView.get(alertController);
- title.setTextColor(0xff33b5e5);
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
當然還有其他辦法,比如直接把title隱藏掉,然後在content View中自定義一個title出來等等
最後更新:2017-04-03 12:56:21