android TextView 支持自定义字体和属性

来源:互联网 发布:独创科技网络 编辑:程序博客网 时间:2024/05/18 14:43

使用android 系统字体:

    Android系统默认支持三种字体,分别为:“sans”, “serif”,  “monospace

eg.

         <!--  使用默认的sans字体-->
        <TextView    android:id="@+id/sans"
                    android:text="Hello,World"
                    android:typeface="sans"
                    android:textSize="20sp">

        </TextView>

 

使用自定义字体属性:

<declare-styleable name="CustomizeTextView">      

      <attr name="fontType">

           <enum name="none" value="0" />

           <enum name="regular" value="1" />

         <enum name="bold" value="2" />

     </attr>   

   </declare-styleable>

 

 

xmls:namespace="http://schemas.android.com/apk/res/project.name.space"

         <!--  使用自定义字体属性-->
        <CustomizeTextView    android:id="@+id/sans"
                    android:text="Hello,World"
                    namespace:fontType="regular"
                    android:textSize="20sp">

        </TextView>

 

使用自定义字体:

             public class CustomizeTextView extends TextView{

 pulibc static TypeFace   typeface1;

 public static TypeFace typeface2;

 {

      typeface1 = Typeface.createFromAsset(context.getAssetManager(), "font/text1.ttf"); 

      typeface2 = Typeface.createFromAsset(context.getAssetManager(), "font/text2.ttf");

}

 

private void init(Context context , AttributeSet attrs , int defStyle)

{

TypedArray a = context.obtainStyledAttributes(attrs,  R.styleable.MyView); 

int fontType = a.getInt(R.styleable.CustomizeTextView_fontType,default);

a.recycle();

switch(fontType){

case 1:

setTypeFace(typeface1);

break;

case 2:

setTypeFace(typeface2);

break;

 default:

           break;

}

 }

}

  

 

 

 

 

0 0