Android Dialog 设置字体大小

时间:2023-02-01 22:14:15

最近在做一个Android的项目,由于经验不足,往往会遇到很多难以解决的问题,就喜欢上CSDN查阅信息,很多时候还是都看到了好的文章顺利解决了问题,我也会把那些对我有帮助的文章收藏。

不巧这次又遇到了一个问题,先看下面图片:

Android Dialog 设置字体大小

这是我在做登录页面的时候,调用系统的ProgressDialog 进行等待,可是看起来很不协调,左边的等待图片过大,右边文字过小,看起来老别扭,虽然功能上不存在什么问题,但是我有强迫症,看不顺的就像弄掉。可是找了好久,没发现 ProgressDialog  有一个方法是可以设置字体的。

于是我又来CSDN查找解决方案,可是找了好久,翻了好几页都没看到想要的结果,心冷了,找到的都说ProgressDialog 可以自定义一个View,在layout定义一个布局,然后设置到ProgressDialog 中,这确实是一个解决办法,可是对我来说颇显麻烦,我只是要一个等待效果,改一下字体,费不着去写一个layout,在重写一个ProgressDialog 吧。

最后我想想,可以设置ProgressDialog  的layout 那么应该也可以获取他的View吧,果然Dialog 就有一个获取View的方法:

public abstract View getDecorView () 
Added in API level 1
Retrieve the top-level window decor view (containing the standard window frame/decorations and the client's content inside of that), which can be added as a window to the window manager.

Note that calling this function for the first time "locks in" various window characteristics as described in

只要有了View 我就可以找到其中的TextView,并设置相应的字体大小,一下是我的实现代码:

    /**
* 显示 进度对话框
* @param message 消息
* @param cancel 是否可取消
* @param textsize 字体大小
*/
protected final void showProgressDialog(String message,boolean cancel,int textsize)
{
// TODO Auto-generated method stub
mProgress = new ProgressDialog(this);
mProgress.setMessage(message);
mProgress.setCancelable(cancel);
mProgress.setOnCancelListener(null);
mProgress.show();

setDialogFontSize(mProgress,textsize);
}
private void setDialogFontSize(Dialog dialog,int size)
{
Window window = dialog.getWindow();
View view = window.getDecorView();
setViewFontSize(view,size);
}
private void setViewFontSize(View view,int size)
{
if(view instanceof ViewGroup)
{
ViewGroup parent = (ViewGroup)view;
int count = parent.getChildCount();
for (int i = 0; i < count; i++)
{
setViewFontSize(parent.getChildAt(i),size);
}
}
else if(view instanceof TextView){
TextView textview = (TextView)view;
textview.setTextSize(size);
}
}

最后看效果图:

Android Dialog 设置字体大小

嘻嘻,这样看起来就比之前好看多了,因为没有早CSDN找到解决办法,就把我的解决方案发到CSDN,希望能帮助到有同样需求的朋友,可能我的方法不是最好的,也希望有朋友指点。