Reputation: 31
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
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.
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>
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