JustAnotherUser
JustAnotherUser

Reputation: 31

Setting attributes of custom views in Android

I've got a class that extends a button. I want to add an additional attribute to it. Is there any way to initialize that attribute from XML? For example:

<MyButton android:id="@+id/myBtn" myValue="Hello World"></MyButton>

public class MyButton extends Button{
private String myValue = "";

public CalcButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}
}

Upvotes: 2

Views: 471

Answers (1)

Aleksander Gralak
Aleksander Gralak

Reputation: 1509

Yes. You can have custom attributes and assign values to it in XML. You can even assign methods to handle custom events on your widgets. Long press definition at XML layout, like android:onClick does

The needed steps.

  1. Implement your custom widget.
  2. Then add file attrs.xml in res/values/ with following content:

    <xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="MyButton">
            <attr name="myValue" format="string"/>
        </declare-styleable>
    </resources>
    
  3. Retrieve values from XML in MyButton constructor. Remember to implement all constructors, not only one.
  4. Use new attribute in your layout xml:

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:custom="http://schemas.android.com/apk/res/**your.package**"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        >
    
        <your.package.MyButton
            android:id="@+id/theId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            custom:myValue="myDoSomething"
        />
        <!-- Other stuff -->
    </LinearLayout>
    

Upvotes: 1

Related Questions