Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use standard attribute android:text in my custom view?

I wrote a custom view that extends RelativeLayout. My view has text, so I want to use the standard android:text without the need to specify a <declare-styleable> and without using a custom namespace xmlns:xxx every time I use my custom view.

this is the xml where I use my custom view:

<my.app.StatusBar     android:id="@+id/statusBar"     android:text="this is the title"/> 

How can I get the attribute value? I think I can get the android:text attribute with

TypedArray a = context.obtainStyledAttributes(attrs,  ???); 

but what is ??? in this case (without a styleable in attr.xml)?

like image 226
Seraphim's Avatar asked Aug 02 '13 09:08

Seraphim's


People also ask

What is Attrs XML in Android?

An <attr> element has two xml attributes name and format . name lets you call it something and this is how you end up referring to it in code, e.g., R. attr. my_attribute . The format attribute can have different values depending on the 'type' of attribute you want.

What is declare Styleable Android?

Keywords: Mobile Android Attribute. 1. declare-style leable defines some attributes, writes some identical attributes together, defines a name, or can be directly defined. In the following two ways, just use declare-style leable to organize similar attributes together.

What is custom view and create it in Android?

Creating custom views. By extending the View class or one of its subclasses you can create your custom view. For drawing view use the onDraw() method. In this method you receive a Canvas object which allows you to perform drawing operations on it, e.g. draw lines, circle, text or bitmaps.


1 Answers

use this:

public YourView(Context context, AttributeSet attrs) {     super(context, attrs);     int[] set = {         android.R.attr.background, // idx 0         android.R.attr.text        // idx 1     };     TypedArray a = context.obtainStyledAttributes(attrs, set);     Drawable d = a.getDrawable(0);     CharSequence t = a.getText(1);     Log.d(TAG, "attrs " + d + " " + t);     a.recycle(); } 

i hope you got an idea

like image 162
pskink Avatar answered Sep 20 '22 16:09

pskink