Android为自定义TextView小部件设置字体

时间:2015-02-06 09:01:51

标签: android android-widget

我用简单的小部件作为textview写了一些属性,我想在扩展的TextView类中为它设置字体,如何做这个动作,我可以有这个能力吗?

atributes:

<resources>
    <declare-styleable name="TextViewStyle">
       <attr name="selected_background" format="integer" />
       <attr name="font"                format="string" />
    </declare-styleable>
</resources>

自定义textview小部件:

public class TextViewStyle extends TextView{

    public TextViewStyle(Context context) {
        super(context);
    }
    public TextViewStyle(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextViewStyle(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewStyle, defStyle, 0);

        a.recycle();
    }
}

简单的UI小部件到xml:

<ir.jaziire.widgets.TextViewStyle
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/topic"
    android:textColor="#000"
    android:textSize="14dp"
    android:gravity="right"
    />

在此小部件中,我想设置app:font=""以设置资产

中的任何字体

3 个答案:

答案 0 :(得分:6)

<强> CustomTextView:

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;

import com.androidhub.R;

public class CustomTextView extends TextView {

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        try {
            TypedArray a = context.obtainStyledAttributes(attrs,
                    R.styleable.font, defStyle, 0);

            String str = a.getString(R.styleable.font_fonttype);
            a.recycle();
            switch (Integer.parseInt(str)) {
            case 0:
                str = "fonts/Trebuchet_MS.ttf";
                break;
            default:
                break;
            }

            setTypeface(FontManager.getInstance(getContext()).loadFont(str));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressWarnings("unused")
    private void internalInit(Context context, AttributeSet attrs) {

    }

<强> FontManager:

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Typeface;

public class FontManager {

    private Map<String, Typeface> fontCache = new HashMap<String, Typeface>();
    private static FontManager instance = null;
    private Context mContext;

    private FontManager(Context mContext2) {
        mContext = mContext2;
    }

    public synchronized static FontManager getInstance(Context mContext) {

        if (instance == null) {
            instance = new FontManager(mContext);
        }
        return instance;
    }

    public Typeface loadFont(String font) {

        if (false == fontCache.containsKey(font)) {
            fontCache.put(font,
                    Typeface.createFromAsset(mContext.getAssets(), font));
        }
        return fontCache.get(font);
    }
}
<{1>}文件中的

attrs.xml

使用<declare-styleable name="font"> <attr name="fonttype"> <enum name="trebuchet_ms" value="0" /> </attr> </declare-styleable> 中的CustomTextView作为:

xml

的顶部声明此内容
xml

您可以将xmlns:custom="http://schemas.android.com/apk/res/com.androidhub" 用作:

CustomTextView

确保将字体放在<com.utils.CustomTextView android:id="@+id/loadMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="@drawable/custom_button_selector" android:clickable="true" android:ellipsize="marquee" android:fadingEdge="horizontal" android:gravity="center" android:marqueeRepeatLimit="marquee_forever" android:padding="10dp" android:scrollHorizontally="true" android:singleLine="true" android:text="@string/load_map" android:textColor="@color/home_buttons_selector" android:textSize="16sp" custom:fonttype="trebuchet_ms" />

assests-->fonts-->YourFont是我的包裹名称。

答案 1 :(得分:3)

我在我的项目中使用它可能对你有用。

TextViewEx.java

   public class TextViewEx extends TextView {
public enum TextStyle {BOLD,LIGHT,REGULAR,SEMIBOLD,EXOREGULAR,BOLDLARGE};
    TypedArray Canvasattrs=null;
    int CurvatureDegree;
    boolean isCurvature = false;
    String direction;
    String RVal;

    public TextViewEx(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TextViewEx(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs){

        if (!this.isInEditMode()) { // used for preview while designing.
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView_TypeFace)
            Typeface font = null;
            String Type = a.getString(R.styleable.TextView_TypeFace_TypeFace);
            if(Type == null){
                UserTypeFace.SetRegular(this); //Set Default Font if font is not defined in xml
                return;
            }

           setStyle(Type);

        } else {
            setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
        }
    }



    private void setStyle(String style){
        TextStyle value = TextStyle.valueOf(style); //convert String to ENUM
        switch (value){

            case BOLD:UserTypeFace.SetBold(this);
                break;
            case LIGHT:UserTypeFace.Setlight(this);
                break;
            case REGULAR:UserTypeFace.Setthin(this);
                break;
            case SEMIBOLD:UserTypeFace.SetSEMIBOLD(this);
                break;
            case EXOREGULAR:UserTypeFace.SetRegular(this);
                break;
            case BOLDLARGE:UserTypeFace.SetBoldLarge(this);
                break;
        }

    }
   }

UserTypeFace.java

public class UserTypeFace {
    public static final String BOLD;
    public static final String LIGHT;
    public static final String REGULAR;
    public static final String EXOREGULAR;
    public static final String BOLDLARGE;
    public static final String SEMIBOLD;

    static {
        REGULAR="fonts/JosefinSans-Bold.ttf";
        LIGHT="fonts/JosefinSans-Bold.ttf";
        BOLD="fonts/JosefinSans-Bold.ttf";
        SEMIBOLD="fonts/JosefinSans-Bold.ttf";
        BOLDLARGE="fonts/JosefinSans-Bold.ttf";
        EXOREGULAR="fonts/Exo2-Regular.ttf";
    }

        private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();

        private static Typeface getTypeFace(Context context, String assetPath) {
            synchronized (cache) {
                if (!cache.containsKey(assetPath)) {
                    try {
                        Typeface typeFace = Typeface.createFromAsset(
                                context.getAssets(), assetPath);
                        cache.put(assetPath, typeFace);
                    } catch (Exception e) {
                        Log.e("TypeFaces", "Typeface not loaded.");
                        return null;
                    }
                }
                return cache.get(assetPath);
            }
        }

    public static void Setthin(TextView obj){
        obj.setTypeface(getTypeFace(obj.getContext(),EXOREGULAR), Typeface.NORMAL);
    }


    public static void Setlight(TextView obj){

        obj.setTypeface(getTypeFace(obj.getContext(),LIGHT), Typeface.NORMAL);
    }


    public static void SetBold(TextView obj){
        obj.setTypeface(getTypeFace(obj.getContext(),BOLD), Typeface.NORMAL);
    }

    public static void SetSEMIBOLD(TextView obj){
        obj.setTypeface(getTypeFace(obj.getContext(),SEMIBOLD), Typeface.NORMAL);
    }
    public static void SetRegular(TextView obj){
        obj.setTypeface(getTypeFace(obj.getContext(),EXOREGULAR), Typeface.NORMAL);
    }

    public static void SetBoldLarge(TextView obj){
        obj.setTypeface(getTypeFace(obj.getContext(),BOLDLARGE), Typeface.BOLD);
    }

    public static Typeface getRegular(View obj){
        return getTypeFace(obj.getContext(),EXOREGULAR);
    }
}

在attrs.xml中添加

 <resources>

    <declare-styleable name="TextView_TypeFace">
        <attr name="TypeFace" format="reference|string" localization="suggested" />

    </declare-styleable>
</resources>

您将在布局文件中添加此内容,如

<pakage.name.TextViewEx
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_gravity="center"
                android:layout_marginBottom="10dp"
                android:textColor="#282828"
                attrs:TypeFace="@string/Bold"
                android:textSize="30sp"
                android:text="  Please Login  "
                android:id="@+id/txtlogin" />

答案 2 :(得分:0)

使用以下代码:

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class MyTextView extends TextView {

    public MyTextView(Context context) {
        super(context);
        createFont();
    }

    public MyTextView(Context context, AttributeSet attr, int defStyle) {
        super(context, attr, defStyle);
        createFont();
    }

    public MyTextView(Context context, AttributeSet attr) {
        super(context, attr);
        createFont();
    }

    private void createFont() {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(), "SHRUTI.TTF");
        setTypeface(font);
    }
}