Fade out/fade in TextView based on scroll

Fade out/fade in TextView based on scroll

我在 LinearLayout 中有一个水平 RecyclerView,上面有一个 TextView,如下所示:

<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="7dp"
 android:layout_marginLeft="10dp"
 android:layout_marginBottom="7dp"
 android:textColor="#FFa7a7a7"
 android:textSize="15sp"
 android:text="Hello, Android" />

<android.support.v7.widget.RecyclerView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/recyclerview"
 android:layout_width="match_parent"
 android:layout_height="185dp" />

我希望 TextView 在向左滚动并且 RecyclerView 中的第一个项目离开视图时淡出。并希望它在第一个项目进入视图时淡入淡出(通过向右滚动)。我知道我将不得不使用 addOnScrollChangedListener() 来确定 recyclerView 的第一项何时离开视图,我无法确定的是淡出(或淡入)TextView 的方法滚动行为。

这是我的 RecyclerView java 片段:

mRecyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(getLayoutManager());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);

编辑:@pskink 是正确的,动画不适用于此特定用例。使用 setAlpha() 是获得所需结果的唯一方法。

您必须将其与 RecyclerView OnScrollListener

放在一起

This answer 应该能帮到你。

看起来最难的部分是确定您在滚动中的确切位置,See this question

OnScrollListener 的通用代码结构,您可能需要反复试验才能将 alpha 值拨入您想要的位置:

float alpha = 1.0f;
float newAlpha = 1.0f;
int overallXScroll = 0;

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
         super.onScrolled(recyclerView, dx, dy);

         //use this value to determine left or right scroll
         overallXScroll = overallXScroll + dx;

         //if scroll left
         float newAlpha = alpha - 0.1f;
         if (newAlpha >= 0){
           textView.setAlpha(newAlpha);
           alpha = newAlpha;
         }

         //if scroll right
         float newAlpha = alpha + 0.1f;
         if (newAlpha <= 1){
           textView.setAlpha(newAlpha);
           alpha = newAlpha;
         }
     }
});