如何在RecyclerView上增大当前聚焦项的大小?

31
我正在尝试使用 RecyclerView 制作一个水平列表,当我将焦点放在一个项目上时,它会增大。我希望实现这种效果:

Increased item effect

你有任何想法来完成这个吗?

我做了完全相同的事情,但对我的“RecyclerList”没有影响。我在我的视图持有者上有一个图像视图,我希望在焦点时它变得更大。请帮帮我! - Sadeq Shajary
嗨@SadeqShajary,也许你应该将focusChangeListener应用于根视图而不是imageView本身。这是在使用遥控器的Android TV上开发和测试的。 - Skycorsarius
4
请不要将解决方案编辑到问题中,您应该将其作为答案发布,以保持与 Stack Overflow 的问答格式一致。 - EJoshuaS - Stand with Ukraine
RecyclerView项的App onTouch事件中是否可以实现此操作? - androholic
2个回答

25

我想象中的是这样的:

  1. 创建水平RV
  2. 在绑定ViewHolder时,将FocusChangeListener附加到项的根视图上
  3. 当项目获得焦点时,将其缩放以使其稍微变大;当失去焦点时,恢复动画。

static class ViewHolder extends RecyclerView.ViewHolder {

  public ViewHolder(View root) {
    // bind views
    // ...

    // bind focus listener
    root.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
        public void onFocusChange(View v, boolean hasFocus) {
          if (hasFocus) {
            // run scale animation and make it bigger
          } else {
            // run scale animation and make it smaller
          }
        }
     });
  }
}

2
这个解决方案只适用于Android TV,而不适用于移动设备... :-( - Pawan
1
@Pawan:你尝试在XML中给根视图添加android:focusable="true"和android:focusableInTouchMode="true"了吗? - Rankush Kumar
2
我不得不加入 android:clickable="true"android:focusableInTouchMode="true" 才能使它工作。 - Yousef Gamal

19
感谢dextor的答案,我终于理解了这个问题。
我使用了FocusChangeListener并添加了动画状态来改变视图的大小:
static class ViewHolder extends RecyclerView.ViewHolder {

public ViewHolder(final View root) {
    // bind views
    // ...

    // bind focus listener
    root.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (hasFocus) {
                 // run scale animation and make it bigger
                 Animation anim = AnimationUtils.loadAnimation(context, R.anim.scale_in_tv);
                 root.startAnimation(anim);
                 anim.setFillAfter(true);
             } else {
                 // run scale animation and make it smaller
                 Animation anim = AnimationUtils.loadAnimation(context, R.anim.scale_out_tv);
                 root.startAnimation(anim);
                 anim.setFillAfter(true);
             }
         }
    });
}

以下是动画代码:

scale_in_tv:

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXScale="100%"
    android:fromYScale="100%"
    android:toXScale="110%"
    android:toYScale="110%"
    android:pivotX="50%"
    android:pivotY="50%">
</scale>

扩展电视规模:

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"
    android:fromXScale="110%"
    android:fromYScale="110%"
    android:toXScale="100%"
    android:toYScale="100%"
    android:pivotX="50%"
    android:pivotY="50%">
</scale>

13
这与我的解决方案有何不同,为什么经过将近一年后被接受的答案(我的)被删除了? - Sebastiano

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