android 字體大小 根據分辨率 自動調整
手機設備太多,分辨率也不一樣,看到網上大部分的適應字體的方法是定義values320×480或value-hdpi方式去處理。
采用第一種的就慘了,很多設備的分辨率是不一樣的,難道要每種都定義嗎?
采用第二種的在平板電腦里沒有效果。
最后還是代碼的方式方便快捷。。。
//遍歷設置字體
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; //字體太小也不好看的 } </pre>
最后在Avtivity的oncreate完后調用一下changeViewSize就行了。。。文字大了那么它對應的背景也就跟著大,所以建議控件的背景圖片用9宮格類型的圖片,看起來舒服。
另外附加,如果你開發的應用想在平板電腦上瀏覽無礙請在AndroidManifest.xml文件中的manifest節點(DTD建議放在application節點上面)里加入:<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:resizeable="true"/>
本文由用戶 ngww 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!