Set background on TextView object and maintain ripple effect

旧巷老猫 提交于 2019-12-07 07:30:48

问题


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);


来源:https://stackoverflow.com/questions/27579626/set-background-on-textview-object-and-maintain-ripple-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!