您的位置:首页 > 移动开发 > Android开发

android字体大小根据分辨率自动调整

2013-12-22 19:00 633 查看
转载:http://hy0664.iteye.com/blog/1360051

之前遇到一个问题,就是:

在app中,显示的文字随着屏幕的尺寸变化而变化。就是说屏幕尺寸越大,字体显示越大,屏幕尺寸越小,字体就越小。

按照常规做法就是我在res文件夹下,分别简历各个尺寸的适配文件夹。

但是.........此处省略千百万字。

so,google一下,觉得下面几个应该可以解决些问题,试了很久,但是还是没能解决我的问题。

Java代码


//遍历设置字体

public static void changeViewSize(ViewGroup viewGroup,int screenWidth,int screenHeight) {//传入Activity顶层Layout,屏幕宽,屏幕高

int adjustFontSize = adjustFontSize(screenWidth,screenHeight);

for(int i = 0; i<viewGroup.getChildCount(); i++ ){

View v = viewGroup.getChildAt(i);

if(v instanceof ViewGroup){

changeViewSize((ViewGroup)v,screenWidth,screenHeight);

}else if(v instanceof Button){//按钮加大这个一定要放在TextView上面,因为Button也继承了TextView

( (Button)v ).setTextSize(adjustFontSize+2);

}else if(v instanceof TextView){

if(v.getId()== R.id.title_msg){//顶部标题

( (TextView)v ).setTextSize(adjustFontSize+4);

}else{

( (TextView)v ).setTextSize(adjustFontSize);

}

}

}

}





//获取字体大小

public static int adjustFontSize(int screenWidth, int screenHeight) {

screenWidth=screenWidth>screenHeight?screenWidth:screenHeight;

/**

* 1. 在视图的 onsizechanged里获取视图宽度,一般情况下默认宽度是320,所以计算一个缩放比率

rate = (float) w/320 w是实际宽度

2.然后在设置字体尺寸时 paint.setTextSize((int)(8*rate)); 8是在分辨率宽为320 下需要设置的字体大小

实际字体大小 = 默认字体大小 x rate

*/

int rate = (int)(5*(float) screenWidth/320); //我自己测试这个倍数比较适合,当然你可以测试后再修改

return rate<15?15:rate; //字体太小也不好看的

}

最后在Avtivity的oncreate完后调用一下changeViewSize就行了。。。文字大了那么它对应的背景也就跟着大,所以建议控件的背景图片用9宫格类型的图片,看起来舒服。

另外附加,如果你开发的应用想在平板电脑上浏览无碍请在AndroidManifest.xml文件中的manifest节点(DTD建议放在application节点上面)里加入:

Java代码


<supports-screens

android:anyDensity="true"

android:largeScreens="true"

android:normalScreens="true"

android:smallScreens="true"

android:resizeable="true"/>

偶然在eoe看到这么一篇帖子:

地址:http://www.eoeandroid.com/thread-291300-1-1.html

这个方法没试。有时间试试、 不想看了,总之,人类已经阻挡不了,那些变态的心了。

其他:http://blog.csdn.net/fmyheart/article/details/8486201
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: