可以将后台Drawable设置为CustomTextView类,该类扩展TextView?

时间:2015-10-08 07:14:29

标签: android xml textview android-custom-view android-drawable

我创建了CustomTextView类并扩展了TextView。

public class CustomTextView extends TextView 

我想以编程方式为此类设置一个可绘制的背景。

我不想在XML文件中设置可绘制 bcoz当我使用这个自定义TextView时,drawable应该自动应用。

bellow是我的CustomTextView类。

public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
        super(context);
        init(null);
    }

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

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

    private void init(AttributeSet attrs){
        if(attrs != null){
            TypedArray tArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextView);
            String typeface  = tArray.getString(R.styleable.CustomTextView_typeface);
            if (typeface != null) {
                Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/"+typeface);
                setTypeface(myTypeface);
            }
            tArray.recycle();
        }
    }
}

我在xml中使用它,如bellow。

<chiragsavsani.customviewlibrary.textview.CustomTextView
        android:id="@+id/txtTextView"
        style="@style/textview_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Typeface TextView"
        customtextview:typeface="Oswald-BoldItalic.ttf" />

rounder_border_textview.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <gradient
        android:angle="270"
        android:endColor="#B6B6B6"
        android:startColor="#D2D5DA" >
    </gradient>

    <corners
        android:bottomLeftRadius="5dip"
        android:bottomRightRadius="5dip"
        android:topLeftRadius="5dip"
        android:topRightRadius="5dip" />

    <stroke
        android:width="1dp"
        android:color="#BABABA" />

</shape>

0 个答案:

没有答案