Saturday, 15 January 2011

Pass attributes to custom Button

In this exercise, a custom Button class with custom attributes will be implemented. It show how to define custom attributes, and how to define the attributes values in main.xml.

custom Button with declare-styleable

First of all, create a attrs.xml in /xml/values/ folder. It define our declare-styleable attributes.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="style_Button">
<attr name="myText_1" format="string" />
<attr name="myText_2" format="string" />
</declare-styleable>
</resources>


Create a new class StyleButton.java, it is our custom Button.
Override the constructor to retrieve the attributes, initStyleButton() method show how to obtain styled attributes via TypedArray. Be sure to call recycle() when done with them.
package com.exercise.AndroidStyleButton;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.Button;

public class StyleButton extends Button {

public StyleButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public StyleButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initStyleButton(attrs);
}

public StyleButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
initStyleButton(attrs);
}

private void initStyleButton(AttributeSet attrs){
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.style_Button);
String Text1 = a.getString(R.styleable.style_Button_myText_1);
String Text2 = a.getString(R.styleable.style_Button_myText_2);
setText(Text1 + "\n" + Text2);
a.recycle();
}

}


Finally, modify main.xml to add our custom buttons with our own attributes.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:stylebutton= "http://schemas.android.com/apk/res/com.exercise.AndroidStyleButton"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
<com.exercise.AndroidStyleButton.StyleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
stylebutton:myText_1="My Text 1"
stylebutton:myText_2="My Text 2"
/>
<com.exercise.AndroidStyleButton.StyleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
stylebutton:myText_1="Hello!"
stylebutton:myText_2="It's a Style Button:)"
/>
</LinearLayout>


Download the files.



No comments:

Post a Comment