图片上面的涟漪效果 - Android

8
我最近在我的边缘项目中尝试使用涟漪动画。对于某些触摸事件的使用,我在寻找“优雅”的解决方案时遇到了一些困难。特别是在列表、网格和回收视图中使用图片。动画几乎总是看起来在视图后面而不是在其上面。这在按钮和文本视图中没有问题,但如果你有一个图像的GridView,则涟漪会出现在实际图像的后面或下面。显然这不是我想要的,虽然有解决办法被认为是一种变通方法,但我希望有更简单的方法,只是我不知道而已。
我使用以下代码来实现具有图像的自定义网格视图。如果您选择,请点击此处获取完整代码CLICK HERE以便跟随。
现在只说重要的事情。为了使我的图像在触摸时进行动画处理,我需要此代码
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/cream_background">
    <item>
        <selector xmlns:android="http://schemas.android.com/apk/res/android">
            <!-- Pressed -->
            <item
                android:drawable="@color/button_selected"
                android:state_pressed="true"/>
            <!-- Selected -->
            <item
                android:drawable="@color/button_selected"
                android:state_selected="true"/>
            <!-- Focus -->
            <item
                android:drawable="@color/button_selected"
                android:state_focused="true"/>
            <!-- Default -->
            <item android:drawable="@color/transparent"/>
        </selector>
    </item>
</ripple>

custom_grid.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:orientation="horizontal">

    <ImageView
        android:id="@+id/sceneGridItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_ripple"
        android:gravity="center_horizontal"/>

</LinearLayout>

activity_main.xml

<GridView
    android:id="@+id/sceneGrid"
    android:layout_marginTop="15dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:verticalSpacing="15dp"
    android:numColumns="5" />

所有的神奇和问题都在我设置背景的那一行代码中发生。虽然这确实在我的imageview上产生了涟漪动画,但它却是在imageview的背后进行的。我希望动画出现在图像的顶部。因此,我尝试了几种不同的方法,比如

将整个网格背景设置为button_ripple。

<GridView
    android:id="@+id/sceneGrid"
    android:layout_marginTop="15dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:verticalSpacing="15dp"
    android:background="@drawable/button_ripple"
    android:numColumns="5" />

它做了你想要的事情,现在整个网格有一个半透明的背景,无论我按哪个图像,整个网格都会从中心动画。虽然这很酷,但这不是我想要的。

将根/父背景设置为button_ripple。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="center_horizontal"
                  android:background="@drawable/button_ripple"
                  android:orientation="horizontal">

该区域现在更大,填充整个网格单元(不仅仅是图片),但它并没有将其置于最前面。

将custom_grid.xml更改为RelativeLayout,并将两个ImageView叠放在一起

custom_grid.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:orientation="horizontal">

    <ImageView
        android:id="@+id/gridItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" />

    <ImageView
        android:id="@+id/gridItemOverlay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:background="@drawable/button_ripple" />

</RelativeLayout>

CustomGridAdapter.java

....
gridItemOverLay = (ImageView) findViewById(R.id.gridItemOverlay);
gridItemOverlay.bringToFront();

这个方法可以实现目标。现在底部的 ImageView 包含了我的图片,而顶部的 ImageView 做动画,成为了一个似乎在我图片上方的涟漪动画。不过,老实说这只是一种变通方法。我觉得这并不是预期的做法。所以我想问问你们有没有更好的方法或其他方式?


请在button_ripple drawable中包含XML。 - alanv
@alanv 已按要求添加。 - Jawascript
<ripple> 元素不是选择器,而是图层列表。请查看 RippleDrawable 的文档。 - alanv
@alanv 我已经阅读了文档,但仍有些困惑。在自定义适配器或多个资源的情况下该怎么做从未清晰地表述过。在这种情况下,我正在使用Android/obb中的扩展文件夹中的位图来填充我的网格。我最好的猜测是使用RippleDrawable构造函数并手动/编程方式应用它,这样正确吗? - Jawascript
我对画廊项目使用了相同的方法。它可以工作,但是涟漪总是从项目的中间开始。你有同样的问题或任何解决方案吗? - Ramesh
4个回答

9

我喜欢安卓开发者的答案,所以我决定调查如何在代码中执行他的解决方案的第二步。

你需要从Jake Wharton这里获取这段代码:https://gist.github.com/JakeWharton/0a251d67649305d84e8a

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;


public class ForegroundImageView extends ImageView {
  private Drawable foreground;


  public ForegroundImageView(Context context) {
    this(context, null);
  } 


  public ForegroundImageView(Context context, AttributeSet attrs) {
    super(context, attrs);


    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ForegroundImageView);
    Drawable foreground = a.getDrawable(R.styleable.ForegroundImageView_android_foreground);
    if (foreground != null) {
      setForeground(foreground);
    } 
    a.recycle();
  } 


  /** 
   * Supply a drawable resource that is to be rendered on top of all of the child 
   * views in the frame layout. 
   * 
   * @param drawableResId The drawable resource to be drawn on top of the children. 
   */ 
  public void setForegroundResource(int drawableResId) {
    setForeground(getContext().getResources().getDrawable(drawableResId));
  } 


  /** 
   * Supply a Drawable that is to be rendered on top of all of the child 
   * views in the frame layout. 
   * 
   * @param drawable The Drawable to be drawn on top of the children. 
   */ 
  public void setForeground(Drawable drawable) {
    if (foreground == drawable) {
      return; 
    } 
    if (foreground != null) {
      foreground.setCallback(null);
      unscheduleDrawable(foreground);
    } 


    foreground = drawable;


    if (drawable != null) {
      drawable.setCallback(this);
      if (drawable.isStateful()) {
        drawable.setState(getDrawableState());
      } 
    } 
    requestLayout();
    invalidate();
  } 


  @Override protected boolean verifyDrawable(Drawable who) {
    return super.verifyDrawable(who) || who == foreground;
  } 


  @Override public void jumpDrawablesToCurrentState() { 
    super.jumpDrawablesToCurrentState(); 
    if (foreground != null) foreground.jumpToCurrentState();
  } 


  @Override protected void drawableStateChanged() { 
    super.drawableStateChanged(); 
    if (foreground != null && foreground.isStateful()) {
      foreground.setState(getDrawableState());
    } 
  } 


  @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (foreground != null) {
      foreground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
      invalidate();
    } 
  } 


  @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    if (foreground != null) {
      foreground.setBounds(0, 0, w, h);
      invalidate();
    } 
  } 


  @Override public void draw(Canvas canvas) {
    super.draw(canvas);


    if (foreground != null) {
      foreground.draw(canvas);
    } 
  } 
} 

这是attrs.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="ForegroundImageView">
    <attr name="android:foreground"/>
  </declare-styleable>
</resources>

现在,在您的layout.xml中创建ForegroundImageView,如下所示:
<com.example.ripples.ForegroundImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop"
    android:foreground="?android:selectableItemBackground"
    android:src="@drawable/apples"
    android:id="@+id/image" />

图像现在将会产生波纹效果。

比将ImageView包装在LayoutGroup中要好得多,后者的性能较慢。 - kenyee

3

我有一个图片库(使用RecyclerViewGridLayoutManager构建)。使用Picasso设置图像。为了给图像添加涟漪效果,我用FrameLayout包装了ImageView。该项布局如下:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:foreground="@drawable/ripple"
    android:clickable="true"
    android:focusable="true"
    >
    <ImageView
        android:id="@+id/grid_item_imageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_gravity="center"
        android:scaleType="centerInside"
        />
</FrameLayout>

请注意android:foreground。它与android:background不同。我已经尝试过不添加android:clickable="true"android:focusable="true"也可以正常工作,但是加上也无妨。
然后在res/drawable中添加一个ripple.xml可绘制文件:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#7FF5AC8E" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</selector>

请注意,在选中项目时(对于Android版本小于5.0的设备),会在图像上方显示半透明颜色。如果您不想要它,可以将其删除。
然后,在res/drawable-v21中添加带有涟漪效果的ripple.xml可绘制文件。
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/coral">
</ripple>

您可以使用默认的涟漪效果,而不是自定义的ripple.xml,但是因为它是灰色的,所以在图片上面很难看清楚:

android:foreground="?android:attr/selectableItemBackground"

3

不需要在适配器中为每个视图添加波纹效果,只需在GridView级别上添加它即可,如下所示:

<GridView
    android:id="@+id/gridview"

    ...

    android:drawSelectorOnTop="true"
    android:listSelector="@drawable/your_ripple_drawable"/>

3
也许可以尝试以下解决方案(从这里获得了提示):
  1. Wrap the drawable in a RippleDrawable² before setting it on the ImageView:

    Drawable image =RippleDrawable rippledImage = new RippleDrawable(
        ColorStateList.valueOf(rippleColor), image, null);
    imageView.setImageDrawable(rippledImage);
    
  2. Extend ImageView and add a foreground attribute to it (like FrameLayout has³). See this example⁴ from +Chris Banes of adding it to a LinearLayout. If you do this then make sure you pass through the touch co-ordinates so that the ripple starts from the correct point:

    @Override
    public void drawableHotspotChanged(float x, float y) {
        super.drawableHotspotChanged(x, y);
        if (foreground != null) {
            foreground.setHotspot(x, y);
        }
    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接