美文网首页
安卓原生AlertDialog修改样式

安卓原生AlertDialog修改样式

作者: 我是少年520 | 来源:发表于2018-04-16 11:18 被阅读983次
    AlertDialog.png

    通过反射和原生的接口修改AlertDialog的样式

    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                            .setTitle("提示")
                            .setMessage("你确认删除本选项吗?")
                            .setPositiveButton("确定", new DialogInterface
                                    .OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO: 2018/4/16 positive
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface
                                    .OnClickListener
                                    () {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO: 2018/4/16 negative
                                }
                            })
                            .create();
                    alertDialog.show();
    
                    alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
                    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.GRAY);
                    try {
                        Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                        mAlert.setAccessible(true);
                        Object mAlertController = mAlert.get(alertDialog);
                        Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
                        mMessage.setAccessible(true);
                        TextView mMessageView = (TextView) mMessage.get(mAlertController);
                        mMessageView.setTextColor(Color.BLACK);
                        Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
                        mTitle.setAccessible(true);
                        TextView mTitleView = (TextView) mTitle.get(mAlertController);
                        mTitleView.setTextColor(Color.BLACK);
                        mTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
    

    相关文章

      网友评论

          本文标题:安卓原生AlertDialog修改样式

          本文链接:https://www.haomeiwen.com/subject/wkvskftx.html