-->

Set background on TextView object and maintain rip

2019-05-06 18:26发布

问题:

I want to set the background of a TextView object programmatically, but also have a ripple effect for it.

I can use with background set to android:selectableItemBackground, but the ripple effect gets lost, when setting the background.

I also tried putting an ImageView together with the TextView in a FrameLayout. And set the image not as the background of the TextView, but as image of the ImageView: Yes, ripple is there, but it appears to be "behind" the image.

Do I need to create a RippleDrawable from the bitmapfor the background? How would I do that?

回答1:

I had same problem as you and fixed it using
android:foreground="?attr/selectableItemBackground" on FrameLayout.

Here is the sample FrameLayout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/more"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground">
    <ImageView
        android:id="@+id/discover_carousel_item_image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_vertical|center_horizontal"
        android:scaleType="fitXY" />
</FrameLayout>


回答2:

RippleDrawable is the solution:

RippleDrawable newImage = new RippleDrawable(
        new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_pressed},
                        new int[]{}
                },
                new int[] {
                        getResources().getColor(R.color.ripple_material_light),
                        getResources().getColor(R.color.ripple_material_dark),
                }),
                new BitmapDrawable(getResources(), mapBitmap),
                null);
textView.setBackground(newImage);