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

拈花ヽ惹草 提交于 2019-11-27 04:16:09

问题


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)?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/18013971/how-to-use-standard-attribute-androidtext-in-my-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!