Possible Duplicate:
How to read custom attributes in Android
Recently I read about custom attributes. I want to add a custom attribute to TextView.
So far I have:
attr file:
<resources>
<attr name="binding" format="string" />
<declare-styleable name="TextView">
<attr name="binding" />
</declare-styleable>
layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/de.innosoft.android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
custom:binding="test"/>
Given a TextView
TextView tv = ...
How would I then get the value of that attribute (which ist "test")? I read about obtainStyledAttributes but do not know exactly how to use it here.
Exactly, you can extend your textview like that
public class CustomTV extends TextView {
public final String YOURATTRS;
public CustomTV(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomTV);
YOURATTRS = ta.getString(R.styleable.CustomTV_binding);
ta.recycle();
// use your attrs or not
}
and the attrs.xml :
<declare-styleable name="CustomTV">
<attr name="binding" format="string"/>
</declare-styleable>
As I know you have 2 options:
TextView and has constructor that takes AttributeSet. Then you can get custom property in this constructor. Check this tutorial: Creating a View Class.Better check this question: How to read custom attributes in Android it's almost the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With