2016-06-23 16 views
15

in XML, spesso faccio questo per emulare onClick effetto:Programatically impostato su Android vista

<android.support.v7.widget.CardView 
    android:id="@+id/cardView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:foreground="?selectableItemBackground"> 

    ... 

</android.support.v7.widget.CardView> 

Esiste un modo per accedere ?selectableItemBackground in java?

risposta

50

Per AppCompat è possibile utilizzare,

TypedValue outValue = new TypedValue(); 
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true); 
cardView.setBackgroundResource(outValue.resourceId); 
+0

link utile, grazie! –

+0

Ho cercato molto e ho trovato molte risposte, ma questo è sicuramente il migliore. Grazie mille! –

0

Provare sotto il codice.

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

Mi dispiace ma questo codice non ha senso per me, che senso ha ottenere 'TypedArray' se non si ottiene alcuna risorsa da esso? –

2

Si dovrebbe fare riferimento come

android.R.attr.selectableItemBackground

0

che stavo cercando la stessa soluzione. Ho leggermente modificato la risposta this per renderla più adatta alla domanda. Chiama il seguente codice dal tuo costruttore.

private void setClickableAnimation(Context context) 
{ 
    TypedValue outValue = new TypedValue(); 
    context.getTheme().resolveAttribute( 
     android.R.attr.selectableItemBackground, outValue, true);   
    setForeground(getDrawable(context, outValue.resourceId)); 
} 
Problemi correlati