Search code examples
androidandroid-attributestypedarray

How to access android resource attributes


I want to access

getContext().obtainStyledAttributes(attrs,android.R.styleable.TextView)

but I am having error in styleable. There is no styleable available in android.R .

I will use this value in my compound view.

public class CustomTextView extends TextView {
 public CustomTextView(Context context) {
    super(context);
    init(null);
 }

 public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs);
 }

 public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs);
 }

 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init(attrs);
 }

 private void init(AttributeSet attrs) {
    if (attrs != null && !isInEditMode()) {
        TypedValue typedValue = new TypedValue();
        int[] textSizeAttr = new int[] { android.R.attr.textSize };
        int indexOfAttrTextSize = 0;
        TypedArray a = getContext().obtainStyledAttributes(typedValue.data, textSizeAttr);
        int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
        a.recycle();
    }
 }

}

layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="hgyanani.customcompoundview.MainActivity">

    <hgyanani.customcompoundview.CustomTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="16sp" />
</RelativeLayout>

Solution

  • You can try like this:

    private void init(AttributeSet attrs) {
    
        if (attrs != null && !isInEditMode()) {
            int[] attrsArray = new int[] {
                    android.R.attr.textSize, // 0
            };
           TypedArray a = getContext().obtainStyledAttributes(attrs, attrsArray);
           int textSize = a.getDimensionPixelSize(0 /*index of attribute in attrsArray*/, View.NO_ID);
      }
    }
    

    textSize will return the value in pixel.

    If you want the exact value of textsize in sp then in the constructor of your custom view (the one that takes in the AttributeSet), you can retrieve the attributes from Android's namespace as such:

    String xmlProvidedSize = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textSize");
    

    The value of the xmlProvidedSize will be something like this "16.0sp" and maybe with little bit of String editing you can just extract the numbers.