I wrote a custom view that extends RelativeLayout
. My view has text, so I want to use the standard android:text
without
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
EDIT
Another way to do it (with specifying a declare-styleable but not having to declare a custom namespace) is as follows:
attrs.xml:
<declare-styleable name="MyCustomView">
<attr name="android:text" />
</declare-styleable>
MyCustomView.java:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
CharSequence t = a.getText(R.styleable.MyCustomView_android_text);
a.recycle();
This seems to be the generic Android way of extracting standard attributes from custom views.
Within the Android API, they use an internal R.styleable class to extract the standard attributes and don't seem to offer other alternatives of using R.styleable to extract standard attributes.
Original Post
To ensure that you get all the attributes from the standard component, you should use the following:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView);
CharSequence t = a.getText(R.styleable.TextView_text);
int color = a.getColor(R.styleable.TextView_textColor, context.getResources().getColor(android.R.color.darker_gray)); // or other default color
a.recycle();
If you want attributes from another standard component just create another TypedArray.
See http://developer.android.com/reference/android/R.styleable.html for details of available TypedArrays for standard components.