Create custom properties for custom controls in the layout

1. Create a new attrs.xml in the values ​​directory

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


height1 is our custom property

2. Create custom controls in the layout file

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


At this time, it cannot be compiled and passed, and the music attribute will report red. This is because the music namespace is not found, so we have to add a namespace ourselves. In the first element of the layout file, add

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


After adding, the compilation can pass, the last paragraph is the package name

3. Create a new class 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();

    }
}



Run, you can see the toast prompt aa=100


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326565133&siteId=291194637