How do I use obtainStyledAttributes(int []) with internal Themes of Android

So I have looked around and found out that android.R.styleable is no longer part of the SDK even though it is still documented here.

That wouldn't really be an issue if it was clearly documented what the alternative is. For example the AOSP Calendar App is still using the android.R.styleable

// Get the dim amount from the theme   
TypedArray a = obtainStyledAttributes(com.android.internal.R.styleable.Theme);
lp.dimAmount = a.getFloat(android.R.styleable.Theme_backgroundDimAmount, 0.5f);
a.recycle();

So how would one get the backgroundDimAmount without getting the int[] from android.R.styleable.Theme?

What do I have to stick into obtainStyledAttributes(int []) in order to make it work with the SDK?


Asked by: Kimberly322 | Posted: 24-01-2022






Answer 1

The CustomView API demo shows how to retrieve styled attributes. The code for the view is here:

https://github.com/android/platform_development/blob/master/samples/ApiDemos/src/com/example/android/apis/view/LabelView.java

The styleable array used to retrieve the text, color, and size is defined in the <declare-styleable> section here:

https://github.com/android/platform_development/blob/master/samples/ApiDemos/res/values/attrs.xml#L24

You can use <declare-styleable> to define any list of attributes that you want to retrieve as a group, containing both your own and ones defined by the platform.

As far as these things being in the documentation, there is a lot of java doc around the styleable arrays that makes them useful to have in the documentation, so they have been left there. However as the arrays change, such as new attributes being added, the values of the constants can change, so the platform ones can not be in the SDK (and please do not use any tricks to try to access them). There should be no need to use the platform ones anyway, because they are each there just for the implementation of parts of the framework, and it is trivial to create your own as shown here.

Answered by: Dainton463 | Posted: 25-02-2022



Answer 2

In the example, they left out the reference to the Context 'c':

public ImageAdapter(Context c) {
    TypedArray a = c.obtainStyledAttributes(R.styleable.GalleryPrototype);
    mGalleryItemBackground = a.getResourceId(
            R.styleable.GalleryPrototype_android_galleryItemBackground, 0);
    a.recycle();
    return mGalleryItemBackground;
}

Changing obtainStyledAttributes to c.obtainStyledAttributes should work

Answered by: Chester196 | Posted: 25-02-2022



Answer 3

Example of pulling out standard attribute (background) in a custom view which has its own default style. In this example the custom view PasswordGrid extends GridLayout. I specified a style for PasswordGrid which sets a background image using the standard android attribute android:background.

public class PasswordGrid extends GridLayout {

    public PasswordGrid(Context context) {
        super(context);
        init(context, null, 0);
    }

    public PasswordGrid(Context context, AttributeSet attrs) {
        super(context, attrs, R.attr.passwordGridStyle);
        init(context, attrs, 0);
    }

    public PasswordGrid(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        if (!isInEditMode()) {

            TypedArray stdAttrs = context.obtainStyledAttributes(attrs,
                    new int[] { android.R.attr.background },  // attribute[s] to access
                    defStyle, 
                    R.style.PasswordGridStyle);  // Style to access

           // or use any style available in the android.R.style file, such as
           //       android.R.style.Theme_Holo_Light

            if (stdAttrs != null) {
                Drawable bgDrawable = stdAttrs.getDrawable(0);
                if (bgDrawable != null)
                    this.setBackground(bgDrawable);
                stdAttrs.recycle();
            }
        }
    }

Here is part of my styles.xml file:

 <declare-styleable name="passwordGrid">
    <attr name="drawOn" format="color|reference" />
    <attr name="drawOff" format="color|reference" />
    <attr name="pathWidth" format="integer" />
    <attr name="pathAlpha" format="integer" />
    <attr name="pathColor" format="color" />
 </declare-styleable>



  <style name="PasswordGridStyle" parent="@android:style/Widget.GridView" >  
      <!--  Style custom attributes.  -->
      <item name="drawOff">@drawable/ic_more</item>
      <item name="drawOn">@drawable/ic_menu_cut</item>
      <item name="pathWidth">31</item>
      <item name="pathAlpha">129</item>
      <item name="pathColor">@color/green</item>

      <!-- Style standard attributes -->
      <item name="android:background">@drawable/pattern_bg</item>
</style>

Answered by: Richard556 | Posted: 25-02-2022



Answer 4

This appears to be a bug in the SDK. I have filed an issue on it, which you may wish to star so as to receive updates on it.

As a worksaround, you can use reflection to access the field:

Class clazz=Class.forName("android.R$styleable");
int i=clazz.getField("Theme_backgroundDimAmount").getInt(clazz);

Answered by: Adelaide653 | Posted: 25-02-2022



Similar questions

android - monodroid/xamarin custom attributes are empty using ObtainStyledAttributes

Trying to pass a custom attribute from a parent layout to a child layout. The TypedArray returned from ObtainStyledAttributes() doesn't seem to have the corresponding custom values for the custom properties I've created, although I can map their IDs to the values in Resource.designer. Attr.xml: &lt;resources&gt; &lt;declare-styleable name="HeaderView"&gt; &lt;attr name="bgcolor" fo...


android - How to access AttributeSet in onClick event handler for use in obtainStyledAttributes?

I have custom attributes set in attrs.xml name custom_values, one of which is named stageNumber. I have a Button with this custom value defined e.g. custom:stageNumber="2" with an onClick handler titled goToStage. In the goToStage method I need to obtain the value of stageNumber. I am unable to fetch the AttributeSet required by the method obtainStyledAttributes. public void goToStage(View view) { Attri...


android - obtainStyledAttributes fails to find arrays

I am writing a custom DialogPreference and I setup the preference with 2 arrays of strings named entries and entryValues, similarly to what a ListPreference would need. Even though both arrays seem to be present when my constructor is called with the AttributeSet param, trying to fetch the styled arrays via obtainStyledAttributes fails by returning null. What am I doing wrong and h...


android custom view obtainStyledAttributes

I'm pretty new to Android and to Java so forgive me if i'm missing something obvious. I want to write a custom View, and i have problems getting the custom attributes via otainStyledAttributes. I have a very simple testcase. In Eclipse i create an empty project (package com.example.customview) with the default activity. Then i added an "attrs.xml" file under res/values with the following content: ...


android - Get multiple style attributes with obtainStyledAttributes

I am trying to obtain several of the style attributes of the android namespace from my code. Here I enclose the relevant extract. AttributeSet attrs is the parameter that is passed in to any custom TextView. private static final int[] ATTRS = new int[] { android.R.attr.textSize, android.R.attr.text, android.R.attr.textColor, android.R.attr.gravity }; private voi...


android - Magic with obtainStyledAttributes method

Code: public class CustomLayoutWithText extends LinearLayout { private Context context; private AttributeSet attrs; public CustomLayoutWithText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; this.attrs = attrs; fooAttrs(); } @Override protected void onFinishInflate() { super.onFinishInflate(); f...


java - obtainStyledAttributes annotated with @StyleableRes. Suppress warnings

While looking at the answer here, I was having problems on the line: TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, attrs); It seems that Android Studio won't let me pass in an int that doesn't come from a R.styleable resource without getti...


android - Why I can't get values fromdeclare styleable TypedArray via obtainStyledAttributes?

I created a custom control, and define some attributes in attri.xml, but I can't get values fromdeclare styleable TypedArray via obtainStyledAttributes, could you help me check what's wrong about my codes? /res/values/attrs.xml &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name="TopBar"&gt; &lt;attr name="title2" format="string" /&gt; &lt;at...


Android : Parse obtainStyledAttributes CardView cardElevation

How does one parse the cardElevation xml attribute programmatically? I've tried the following to no avail: int elevation = getDimension(context, attrs, new int[]{android.support.v7.cardview.R.styleable.CardView_cardElevation}); int elevation = getDimension(context, attrs, new int[]{android.support.v7.cardview.R.attr.cardElevation}); private int getDimension(Context context, AttributeSet attrs, int[] sys...


What is proper way to call obtainStyledAttributes() in Android custom views

What is the difference between TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0); and TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyleAttr, 0);






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top