Android 根据屏幕分辨率自动调整字体大小

1、在oncreate 里获取手机屏幕宽和高度

1 DisplayMetrics dm = new DisplayMetrics();
2 getWindowManager().getDefaultDisplay().getMetrics(dm);// 取得窗口属性
3 int screenWidth = dm.widthPixels;// 窗口的宽度
4 int screenHeight = dm.heightPixels;// 窗口高度

2、在oncreate后获取Activity的Layout

1 ViewGroup viewGroup=(ViewGroup)this.findViewById(android.R.id.content);
2 ChangeView.changeViewSize(viewGroup, screenWidth, screenHeight);

3、ChangeView 代码如下

 1 public class ChangeView {
 2     // 遍历设置字体
 3     public static void changeViewSize(ViewGroup viewGroup, int screenWidth,
 4             int screenHeight) {// 传入Activity顶层Layout,屏幕宽,屏幕高
 5         int adjustFontSize = adjustFontSize(screenWidth, screenHeight);
 6         for (int i = 0; i < viewGroup.getChildCount(); i++) {
 7             View v = viewGroup.getChildAt(i);
 8             if (v instanceof ViewGroup) {
 9                 changeViewSize((ViewGroup) v, screenWidth, screenHeight);
10             } else if (v instanceof Button) {// 按钮加大这个一定要放在TextView上面,因为Button也继承了TextView
11                 ((Button) v).setTextSize(adjustFontSize + 2);
12             } else if (v instanceof TextView) {
13                 ((TextView) v).setTextSize(adjustFontSize);
14                 /*
15                  * if(v.getId()== R.id.title_msg){//顶部标题 ( (TextView)v
16                  * ).setTextSize(adjustFontSize+4); }else{ ( (TextView)v
17                  * ).setTextSize(adjustFontSize); }
18                  */
19             }
20         }
21     }
22 
23     // 获取字体大小
24     public static int adjustFontSize(int screenWidth, int screenHeight) {
25         screenWidth = screenWidth < screenHeight ? screenWidth : screenHeight;
26         /**
27          * 1. 在视图的 onsizechanged里获取视图宽度,一般情况下默认宽度是320,所以计算一个缩放比率 rate = (float)
28          * w/320 w是实际宽度 2.然后在设置字体尺寸时 paint.setTextSize((int)(8*rate));
29          * 8是在分辨率宽为320 下需要设置的字体大小 实际字体大小 = 默认字体大小 x rate
30          */
31         int rate = (int) (5 * (float) screenWidth / 320); // 我自己测试这个倍数比较适合,当然你可以测试后再修改
32         return rate < 15 ? 15 : rate; // 字体太小也不好看的
33     }
34 }
35 //方法转自http://hy0664.iteye.com/blog/1360051

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

1 <supports-screens
2         android:anyDensity="true"
3         android:largeScreens="true"
4         android:normalScreens="true"
5         android:smallScreens="true" 
6         android:resizeable="true"/>

 

转载于:https://www.cnblogs.com/eachann/p/4142320.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值