Parameters via xml for custom Imageview

Asked

Viewed 137 times

2

I have a ImageView customized, which will function as a Switch.

On the screen, I will have several of this item, but of 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!

  • you tried android:background="@android:color/black" ?

1 answer

2


It is possible to create custom attributes.
For this it is necessary to declare a Attribute Resource:

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

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

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

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 inserting the Switchcustom in a layout, to have access to the attribute, you must indicate in the layout the namespace to which he 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.