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

手机设备太多,分辨率也不一样,看到网上大部分的适应字体的方法是定义values320×480或value-hdpi方式去处理。 
采用第一种的就惨了,很多设备的分辨率是不一样的,难道每种都定义吗? 
采用第二种的在平板电脑里没有效果。 

最后还是代码的方式方便快捷:

[java]  view plain copy
  1. //遍历设置字体  
  2. public static void changeViewSize(ViewGroup viewGroup,int screenWidth,int screenHeight) {
  3. //传入Activity顶层Layout,屏幕宽,屏幕高  
  4.         int adjustFontSize = adjustFontSize(screenWidth,screenHeight);  
  5.         for(int i = 0; i<viewGroup.getChildCount(); i++ ){  
  6.             View v = viewGroup.getChildAt(i);  
  7.             if(v instanceof ViewGroup){  
  8.                 changeViewSize((ViewGroup)v,screenWidth,screenHeight);  
  9.             }else if(v instanceof Button){//按钮加大这个一定要放在TextView上面,因为Button也继承了TextView  
  10.                 ( (Button)v ).setTextSize(adjustFontSize+2);  
  11.             }else if(v instanceof TextView){  
  12.                 if(v.getId()== R.id.title_msg){//顶部标题  
  13.                     ( (TextView)v ).setTextSize(adjustFontSize+4);  
  14.                 }else{  
  15.                     ( (TextView)v ).setTextSize(adjustFontSize);  
  16.                 }  
  17.             }  
  18.         }  
  19.     }  
  20.   
  21.   
  22. //获取字体大小  
  23. public static int adjustFontSize(int screenWidth, int screenHeight) {  
  24.         screenWidth=screenWidth>screenHeight?screenWidth:screenHeight;  
  25.         /** 
  26.          * 1. 在视图的 onsizechanged里获取视图宽度,一般情况下默认宽度是320,所以计算一个缩放比率 
  27.             rate = (float) w/320   w是实际宽度 
  28.            2.然后在设置字体尺寸时 paint.setTextSize((int)(8*rate));   8是在分辨率宽为320 下需要设置的字体大小 
  29.             实际字体大小 = 默认字体大小 x  rate 
  30.          */  
  31.         int rate = (int)(5*(float) screenWidth/320); //我自己测试这个倍数比较适合,当然你可以测试后再修改  
  32.         return rate<15?15:rate; //字体太小也不好看的  
  33. }  
最后在Avtivity的oncreate完后调用一下changeViewSize就行了。。。文字大了那么它对应的背景也就跟着大,所以建议控件的背景图片用9宫格类型的图片,看起来舒服。 
另外附加,如果你开发的应用想在平板电脑上浏览无碍请在AndroidManifest.xml文件中的manifest节点(DTD建议放在application节点上面)里加入: 
[java]  view plain copy
  1. <supports-screens  
  2.         android:anyDensity="true"  
  3.         android:largeScreens="true"  
  4.         android:normalScreens="true"  
  5.         android:smallScreens="true"   
  6.         android:resizeable="true"/>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值