2

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);
}
}

1 Answer 1

1

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>
    
Sign up to request clarification or add additional context in comments.

2 Comments

how do you actually fetch custom:myValue within the MyButton class?
@GeniaS. please look at the link I have provided. There is a full code example with retreiving valuse from xml in constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.