Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android custom attribute for TextView [duplicate]

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.

like image 203
cdbeelala89 Avatar asked May 25 '26 07:05

cdbeelala89


2 Answers

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>
like image 143
Goo Avatar answered May 27 '26 19:05

Goo


As I know you have 2 options:

  • Create your own view that extends TextView and has constructor that takes AttributeSet. 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.

like image 34
Mikita Belahlazau Avatar answered May 27 '26 19:05

Mikita Belahlazau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!