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"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM