android 字体总结

Android提供三种字体:“Sans”,“serif“和“monospace”。 默认:Sans

1、在Android XML文件中设置字体

<TextView
                android:id="@+id/t1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="hello_world!您好,世界!(sans)"
                android:typeface="sans" />

<TextView
                android:id="@+id/t2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="hello_world!您好,世界!(serif)"
                android:typeface="serif" />

<TextView
                android:id="@+id/t3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="hello_world!您好,世界!(monospace)"
                android:typeface="monospace" />

2、自定义字体
  1)将新字体的TTF文件copy到assets/fonts/目录下面。
  2)我们需要将widget设置为该字体,比较遗憾的是,不能直接在XML文件中进行,需要编写源代码。

typeface= Typeface.createFromAsset(getAssets(), "fonts/lz.ttf");

textView.setTypeface(typeface);

3. UI所有组件使用自定义字体

3.1 方法
public static void changeFonts(ViewGroup root, Activity act) { 
       Typeface tf = Typeface.createFromAsset(act.getAssets(), 
              "fonts/lz.ttf"); 
       for (int i = 0; i < root.getChildCount(); i++) { 
           View v = root.getChildAt(i); 
           if (v instanceof TextView) { 
              ((TextView) v).setTypeface(tf); 
           } else if (v instanceof Button) { 
              ((Button) v).setTypeface(tf); 
           } else if (v instanceof EditText) { 
              ((EditText) v).setTypeface(tf); 
           } else if (v instanceof ViewGroup) { 
              changeFonts((ViewGroup) v, act); 
           } 
       } 
    } 
}
3.2 activity中调用方法

     ViewGroup viewGroup=(ViewGroup)findViewById(android.R.id.content);
     FontManager.changeFonts(viewGroup, this);

4. html的使用

        String str = "测试<b>黑体字</b>、<i>斜体字</i>、<u>下划 线</u>、<font color='red'>红色字</font>的显示。" ;

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

猜你喜欢

转载自myhearsnow.iteye.com/blog/2092507