初學自定義view(自定義屬性)

1.values下面建attrs

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomViewBottom">
        <attr name="buttonNum" format="integer"></attr>
        <attr name="itemBackGround" format="reference|color"></attr>
    </declare-styleable>
</resources>
2.創建一個類

public class CustomViewBottom extends Button {
    public CustomViewBottom(Context context) {
        super(context);
    }

    public CustomViewBottom(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(attrs);
    }

    private void initView(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomViewBottom);
        int num = typedArray.getInt(R.styleable.CustomViewBottom_buttonNum, 10);
        int resourceId = typedArray.getResourceId(R.styleable.CustomViewBottom_itemBackGround, 1);
        //給屬性賦值
        setText(num+"");
        setBackgroundResource(resourceId);

        typedArray.recycle();
    }

    public CustomViewBottom(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(attrs);
    }
}
3.佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:butt="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   <com.2017040901.view.CustomViewBottom
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       butt:buttonNum="40"
       butt:itemBackGround="@color/colorAccent"
       >
   </com.2017040901.view.CustomViewBottom>
</RelativeLayout>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章