3

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.

Community
  • 1
  • 1
cdbeelala89
  • 2,066
  • 3
  • 28
  • 39

2 Answers2

5

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>
Goo
  • 1,318
  • 1
  • 13
  • 31
3

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.

Community
  • 1
  • 1
Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
  • thank you very much vor the link to the other post. Seems I need that. But still I don't know how to get the custom attribute value e.g. for a textview. (with obtainStyledAttributes ?) – cdbeelala89 Jan 16 '13 at 14:46
  • @cdbeelala89 check tutorial I mentioned in answer. Bacically you create calss `MyTextView` that extends `TextView` and implement constructor that takes context and attributes and use `obtainStyledAttributes` to ge thandy `TypedArray`. – Mikita Belahlazau Jan 16 '13 at 14:48
  • How can we set a custom attribute value programmatically? – Mohammad Afrashteh Jun 01 '18 at 05:55