Android custom attribute for TextView
11,179
Solution 1
As I know you have 2 options:
- Create your own view that extends
TextView
and has constructor that takesAttributeSet
. Then you can get custom property in this constructor. Check this tutorial: Creating a View Class. - Implement own LayoutInfalter.Factory where you handle custom attributes.
Better check this question: How to read custom attributes in Android it's almost the same.
Solution 2
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>
Author by
cdbeelala89
Updated on June 04, 2022Comments
-
cdbeelala89 almost 2 years
Possible Duplicate:
How to read custom attributes in AndroidRecently 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.