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

后端 未结 2 1336
礼貌的吻别
礼貌的吻别 2020-12-01 01:46

I wrote a custom view that extends RelativeLayout. My view has text, so I want to use the standard android:text without

相关标签:
2条回答
  • 2020-12-01 02:23

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题