创建自定义控件在布局中的自定义属性

1.在values目录下新建attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MusicView">
        <attr name="height1" format="integer" />
    </declare-styleable>
</resources>


height1就是我们的自定义属性

2.在布局文件中创建自定义控件

    <demo.com.selfdefineview.MyView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        music:height1="100"
        />


这个时候是无法编译通过的,music属性会报红,这是因为没有找到music命名空间的缘故,所以我们要自己要加一个命名空间,在布局文件的第一个元素内,加上

  xmlns:music="http://schemas.android.com/apk/res/demo.com.selfdefineview"


加上后,编译就可以通过,最后一段是包名

3.新建一个类MyView


public class MyView extends View {

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

    public MyView(Context context, AttributeSet attrs){

        super(context,attrs);


        TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MusicView);
       int aa = ta.getInteger(R.styleable.MusicView_height1,0);


        Toast.makeText(context,"aa="+aa,Toast.LENGTH_LONG).show();

    }
}



运行,此时可以看到toast提示aa=100


猜你喜欢

转载自n-wang.iteye.com/blog/2323832