从XML获取自定义textview的自定义属性

Ded*_*mar 3 java android textview

如何获取自定义fontname自定义TextView的属性设置字体到Textview. 基于Attributes值设置TextView中的Font

public class MyTextView extends TextView
{
    public MyTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

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

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

    public void init()
    {
          // set font_name based on attribute value of textview in xml file
          String font_name = "";
        if (!isInEditMode())
        {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                    "fonts/"+font_name);
            setTypeface(tf);
        }
    }
Run Code Online (Sandbox Code Playgroud)

在Xml文件中

<com.Example.MyTextView 
            android:id="@+id/header"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            fontname="font.ttf"
            android:text="Header"   
/>
Run Code Online (Sandbox Code Playgroud)

我也把font.ttf文件放在assets-> fonts 谢谢你

Jav*_*tor 5

1.将readAttr(context,attrs)方法添加到您的构造函数中,如下所示.

public MyTextView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    readAttr(context,attrs);
    init();
}

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

public MyTextView(Context context)
{
    super(context);
    init();
}
Run Code Online (Sandbox Code Playgroud)

2.在同一个类中定义readAttr()方法.

private void readAttr(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);

    // Read the title and set it if any
    String fontName = a.getString(R.styleable.MyTextView_fontname) ;
    if (fontName != null) {
        // We have a attribute value and set it to proper value as you want
    }

    a.recycle();
}
Run Code Online (Sandbox Code Playgroud)

3.修改attrs.xml文件(res/values/attrs.xml)并将以下内容添加到文件中

<declare-styleable name="MyTextView">
  <attr name="fontname" format="string" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

4.在Xml文件中.

<com.Example.MyTextView 
   android:id="@+id/header"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   custom:fontname="font.ttf"
   android:text="Header" />
Run Code Online (Sandbox Code Playgroud)

5.将此行添加到xml文件的顶部容器中.

xmlns:custom="http://schemas.android.com/apk/res/com.yourpackage.name"
Run Code Online (Sandbox Code Playgroud)

就这样