2013-12-11 3 views
40

android.R.attr.selectableItemBackground существует, но как добавить его программно в ImageButton?Как я могу добавить selectableItemBackground к ImageButton программно?

Кроме того, как я могу найти ответ в документации? Это упоминается here, но я не вижу никакого объяснения того, как оно используется на самом деле. На самом деле, я редко вижу, что документация полезна, но я надеюсь, что это моя вина, а не документация.

+1

возможно дубликат: HTTP: // stackoverflow.com/questions/9398610/how-to-get-the-attr-reference-in-code –

+0

Обратите внимание, что мой вопрос состоит из двух частей, второй нет t в другой теме. – abc32112

+0

добавил пример –

ответ

45

Вот пример использования ответ здесь: How to get the attr reference in code?

// 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); 
+11

Это не сработало, по крайней мере, на Lollipop с AppCompat. Тем не менее, [это сделал.] (Http://stackoverflow.com/a/28087443/1489860) –

+0

Код работает отлично для меня на Lollipop с AppCompat (май 2017 г.) - только разница была я использую 'View.setForeground (Drawable)' вместо 'setBackground()' –

42

Если вы используете AppCompat вы можете использовать следующий код:

int[] attrs = new int[]{R.attr.selectableItemBackground}; 
TypedArray typedArray = context.obtainStyledAttributes(attrs); 
int backgroundResource = typedArray.getResourceId(0, 0); 
view.setBackgroundResource(backgroundResource); 
typedArray.recycle(); 
+2

Я использую AppCompat Theme, и он не работает для меня –

+5

@Renges вы должны установить флаги 'setClickable (true)' и 'setFocusable (true)' – Pedram

+0

Thanx, это помогло! – Harry

6

Это работает для меня с моим TextView:

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

clickableTextView.setClickable(true); 
clickableTextView.setBackgroundResource(typedValue.resourceId); 

Поскольку я использую библиотеку AppCompat, я использую R.attr.selectableItemBackground нет android.R.attr.selectableItemBackground.

Я думаю typedValue.resourceId держит все из selectableItemBackground вводимых коэффициента, чем при использовании TypeArray#getResourceId(index, defValue) или TypeArray#getDrawable(index), которые считывают только растяжимый в данных index.

0

Используйте это расширение функции в Котлин

fun View.setBackgroundResource() { 
    val outValue = TypedValue() context.theme.resolveAttribute(R.attr.selectableItemBackground,outValue,true) 
    this.backgroundResource = outValue.resourceId 
} 
0

Попробуйте этот метод:

public Drawable getDrawableFromAttrRes(int attrRes, Context context) { 
    TypedArray a = context.obtainStyledAttributes(new int[] {attrRes}); 
    try { 
     return a.getDrawable(0); 
    } finally { 
     a.recycle(); 
    } 
} 

// Тогда просто называют это так:

getDrawableFromAttrRes(R.attr.selectableItemBackground, context) 

// Example 
ViewCompat.setBackground(view,getDrawableFromAttrRes(R.attr.selectableItemBackground, context)) 
Смежные вопросы