通过 findViewById 获取 AlertDialog 标题

6

我曾试图通过使用下面这个函数来改变AlertDialog的字体

private void saveDialog(){

    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
        builder.setTitle(res.getString(R.string.dialog_title))
               .setMessage(res.getString(R.string.dialog_saveconfirm)) 
               .setCancelable(false)
               .setNegativeButton(res.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                 }
               })
               .setPositiveButton(res.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //do some thing
            });
        AlertDialog alert = builder.create();
        alert.show();

        TextView tit = (TextView) alert.findViewById(android.R.id.title);
        TextView msg = (TextView) alert.findViewById(android.R.id.message);
        Button btn2 = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
        Button btn1 = alert.getButton(DialogInterface.BUTTON_POSITIVE);
        tit.setTypeface(UtiliShare.getTf());
        msg.setTypeface(UtiliShare.getTf());
        btn1.setTypeface(UtiliShare.getTf());
        btn2.setTypeface(UtiliShare.getTf());

}

当我在Activity中调用函数时,当设置字体类型时,tit出现了02-25 17:59:04.759: E/AndroidRuntime(1014): java.lang.NullPointerException,但是当我删除tit时,对话框工作良好。
我认为错误出现在TextView tit = (TextView) alert.findViewById(android.R.id.title);,它返回null。
我该如何解决这个问题?? 更新: 此链接包含了我的问题的答案:答案 感谢Sam

我不相信Android会让你像这样访问这些TextView,但是你应该能够使用样式和主题来实现你想要的:更改AlertDialog的样式 - Sam
这里的我的帖子可能会对你有所帮助:https://dev59.com/UG865IYBdhLWcg3wBJ4q#13359573 - SingleWave Games
3
这个答案声称你可以使用alertTitle代替title来改变AlertDialog的字体大小:Changing font size into an AlertDialog。(我自己没有尝试过。) - Sam
谢谢Sam,现在它对我有用了。你救了我的一天。 - AwadKab
@Sam。alertTitle的答案对于获取View起作用了,但仍存在一个问题,我在答案中已经指出。 - Stephen Hosking
2个回答

1

请查看Sam的评论。谢谢。 - AwadKab

0
如果你正在使用 android.support.v7.app.AlertDialog,则必须使用 android.support.v7.appcompat.R.id.alertTitle,否则请使用 android.R.id.title

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接