如何以编程方式将selectableItemBackground添加到ImageButton?

abc*_*112 49 android attr r.java-file

android.R.attr.selectableItemBackground存在,但是如何以编程方式将其添加到ImageButton?

另外,我将如何在文档中找到答案?这里提到,但我没有看到它是如何实际使用的任何解释.实际上,我似乎很少发现文档有用,但我希望这是我的错,而不是文档的错.

Tim*_*çin 53

以下是使用答案的示例:如何在代码中获取attr引用?

    // Create an array of the attributes we want to resolve
    // using values from a theme
    // android.R.attr.selectableItemBackground requires API LEVEL 11
    int[] attrs = new int[] { android.R.attr.selectableItemBackground /* index 0 */};

    // Obtain the styled attributes. 'themedContext' is a context with a
    // theme, typically the current Activity (i.e. 'this')
    TypedArray ta = obtainStyledAttributes(attrs);

    // Now 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 resources used by TypedArray
    ta.recycle();

    // setBackground(Drawable) requires API LEVEL 16, 
    // otherwise you have to use deprecated setBackgroundDrawable(Drawable) method. 
    imageButton.setBackground(drawableFromTheme);
    // imageButton.setBackgroundDrawable(drawableFromTheme);
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用,至少在Lollipop上使用AppCompat.但是,[这确实.](http://stackoverflow.com/a/28087443/1489860) (12认同)

And*_*y T 50

如果您使用的是AppCompat,则可以使用以下代码:

int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
view.setBackgroundResource(backgroundResource);
typedArray.recycle();
Run Code Online (Sandbox Code Playgroud)

  • @Renges你应该设置标志`setClickable(true)`和`setFocusable(true)` (5认同)
  • 我使用AppCompat主题,它不适合我 (2认同)

mao*_*eng 8

这适用于我TextView:

// Get selectable background
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);

clickableTextView.setClickable(true);
clickableTextView.setBackgroundResource(typedValue.resourceId);
Run Code Online (Sandbox Code Playgroud)

因为我使用AppCompat库,所以我R.attr.selectableItemBackground没有使用android.R.attr.selectableItemBackground.

我认为typedValue.resourceId拥有所有的drawables selectableItemBackground比使用TypeArray#getResourceId(index, defValue)或者TypeArray#getDrawable(index)只检索给定的drawable index.