android 字型大小,樣式 ,像素的設定

來源:互聯網
上載者:User

 /**
  * 私人構造方法
  * 
  * @param activity
  */
 private MySystemParams(Activity activity) {
  DisplayMetrics dm = new DisplayMetrics();
  activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
  screenWidth = dm.widthPixels;
  screenHeight = dm.heightPixels;
  densityDpi = dm.densityDpi;
  scale = dm.density;
  fontScale = dm.scaledDensity;

  screenOrientation = screenHeight > screenWidth ? SCREEN_ORIENTATION_VERTICAL
    : SCREEN_ORIENTATION_HORIZONTAL;
 }

通常在代碼中設定組件或文字大小隻能用px,通過這個工具類我們可以把dip(dp)或sp為單位的值轉換為以px為單位的值而保證大小不變。方法中的參數請參考http://www.cnblogs.com/wader2011/archive/2011/11/28/2266669.html

代碼

/**
 * Android大小單位轉換工具類
 * 
 * @author wader
 * 
 */
public class DisplayUtil {
 /**
  * 將px值轉換為dip或dp值,保證尺寸大小不變
  * 
  * @param pxValue
  * @param scale(DisplayMetrics類中屬性density)
  * @return
  */
 public static int px2dip(float pxValue, float scale) {
  return (int) (pxValue / scale + 0.5f);
 }

 /**
  * 將dip或dp值轉換為px值,保證尺寸大小不變
  * 
  * @param dipValue
  * @param scale(DisplayMetrics類中屬性density)
  * @return
  */
 public static int dip2px(float dipValue, float scale) {
  return (int) (dipValue * scale + 0.5f);
 }

 /**
  * 將px值轉換為sp值,保證文字大小不變
  * 
  * @param pxValue
  * @param fontScale(DisplayMetrics類中屬性scaledDensity)
  * @return
  */
 public static int px2sp(float pxValue, float fontScale) {
  return (int) (pxValue / fontScale + 0.5f);
 }

 /**
  * 將sp值轉換為px值,保證文字大小不變
  * 
  * @param spValue
  * @param fontScale(DisplayMetrics類中屬性scaledDensity)
  * @return
  */
 public static int sp2px(float spValue, float fontScale) {
  return (int) (spValue * fontScale + 0.5f);
 }
}

 用Html來格式化字元,例如要實現如下的顯示: 

"這隻是一個測試字串,測試黑體字、斜體字、底線、紅色字的顯示。" 

可以將字串格式化成Html格式,如下: 

String source = "這隻是一個測試字串,測試<b>黑體字</b>、<i>斜體字</i>、<u>底線</u>、<font color='red'>紅色字</font>的顯示。";
 

textView.setText(Html.fromHtml(source));
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.