Android 自定義View(二)

標籤屬性篇

java代碼:

Values attrs

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="TitleText" format="string|reference"/>
    <attr name="TitleTextColor" format="color|reference"/>
    <attr name="TitleTextSize" format="dimension|reference"/>

    <declare-styleable name="TestTitleView">
        <attr name="TitleText"/>
        <attr name="TitleTextColor"/>
        <attr name="TitleTextSize"/>
    </declare-styleable>
</resources>

View代碼:

/**
 * Created by aierJun on 2017/2/15.
 */
public class TestTitleView extends RelativeLayout {
    private TextView back;
    private TextView title;

    public TestTitleView(Context context) {
        super(context);
    }

    public TestTitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.test_text_title_view, this);
        back= (TextView)findViewById(R.id.back_test_view);
        title= (TextView)findViewById(R.id.title_test_view);
        TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.TestTitleView);
        int textColor=a.getColor(R.styleable.TestTitleView_TitleTextColor, Color.BLUE);
        String textText=a.getString(R.styleable.TestTitleView_TitleText);
        float textSize=a.getDimension(R.styleable.TestTitleView_TitleTextSize,25);
        title.setTextSize(textSize);
        title.setTextColor(textColor);
        title.setText(textText);
        a.recycle();
    }

    public TestTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void setBackOnClickLister(OnClickListener lister){
        back.setOnClickListener(lister);
    }
}

Layout代碼:

 <com.aierjun.test.view.TestTitleView
        android:id="@+id/test_testtitleview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:TitleTextSize="19sp"
        app:TitleText="aierjun">
    </com.aierjun.test.view.TestTitleView>

注意:

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

最後

a.recycle();
發佈了49 篇原創文章 · 獲贊 23 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章