初学自定义view(自定义属性)

来源:互联网 发布:淘宝店铺营销策划方案 编辑:程序博客网 时间:2024/04/30 00:12

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>

0 0
原创粉丝点击