Parameters via xml for custom ImageView

2

I have% custom%, which will work as ImageView .

On the screen, I will have several of this item, but different colors.

I wonder if it is possible to pass a color parameter in the xml declaration.

Example:

<com.example.utils.SwitchCustom
        android:layout_margin="15dp"
        android:layout_width="150dp"
        android:layout_height="50dp" 
        cordefundo="azul"/>

Thank you!

    
asked by anonymous 28.10.2015 / 12:41

1 answer

2

You can create custom attributes. For this you need to declare an Attribute Resource :

In the res/value folder, create a file named attrs.xml with the following content:

<resources>
   <declare-styleable name="SwitchCustom">
       <attr name="cordefundo" format="color" />
   </declare-styleable>
</resources>

In the SwitchCustom java code you can access the value of this attribute in the SwitchCustom(Context context, AttributeSet attrs) constructor:

private int cordefundo;

public SwitchCustom(Context context, AttributeSet attrs){
    super(context, attrs);

    TypedArray a = context.getTheme()
                          .obtainStyledAttributes(attrs, R.styleable.SwitchCustom, 0, 0);

    try {
        cordefundo = a.getInteger(R.styleable.SwitchCustom_cordefundo, 0);
    } finally {
        a.recycle();
    }
}

When you put the SwitchCustom in a layout , to access the attribute, you must indicate in the layout the namespace to which it belongs :

xmlns:custom="http://schemas.android.com/apk/res/com.example.utils"

Example for a LinearLayout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:custom="http://schemas.android.com/apk/res/com.example.utils">

    <com.example.utils.SwitchCustom
        android:layout_margin="15dp"
        android:layout_width="150dp"
        android:layout_height="50dp" 
        custom:cordefundo="@android:color/blue"/>

</LinearLayout>
    
28.10.2015 / 13:23