更改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出来等等
本文介绍了一种通过反射机制获取AlertDialog内部组件的方法,从而实现自定义标题颜色等特性。此外还提到了另一种方案,即直接隐藏默认标题并在ContentView中自行创建标题。
706

被折叠的 条评论
为什么被折叠?



