How to get the attr reference in code?

前端 未结 2 859
逝去的感伤
逝去的感伤 2020-12-04 15:14

I\'m looking to get the pointing reference from an attribute via code. In my xml layouts I can easily get the referenced drawable like this:

android:backgrou         


        
相关标签:
2条回答
  • 2020-12-04 16:02

    Shouldn't you use:

    android:background="@drawable/listItemBackground"

    And then:

    myImageButton.getBackgroundDrawable()

    Or maybe I didn't understand ...

    0 讨论(0)
  • 2020-12-04 16:11

    This is how you do it:

    // Create an array of the attributes we want to resolve
    // using values from a theme
    int[] attrs = new int[] { R.attr.listItemBackground /* index 0 */};
    
    // Obtain the styled attributes. 'themedContext' is a context with a
    // theme, typically the current Activity (i.e. 'this')
    TypedArray ta = themedContext.obtainStyledAttributes(attrs);
    
    // To get the value of the 'listItemBackground' attribute that was
    // set in the theme used in 'themedContext'. The parameter is the index
    // of the attribute in the 'attrs' array. The returned Drawable
    // is what you are after
    Drawable drawableFromTheme = ta.getDrawable(0 /* index */);
    
    // Finally, free the resources used by TypedArray
    ta.recycle();
    
    0 讨论(0)
提交回复
热议问题