I have a horizontal RecyclerView in a LinearLayout with a TextView above it, like this:
<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" />
I want the TextView to fade out when there is a left scroll and the first item in the RecyclerView goes out of view. And want it to fade back in whenever the first item comes into view(through a right scroll). I know that I will have to use addOnScrollChangedListener()
to determine when the first item of the recyclerView goes out of view, what I haven't been able to determine is a way to fade out(or fade in) the TextView with the scroll behaviour.
Here's my RecyclerView java snippet:
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(getLayoutManager());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
Edit: @pskink is correct, an Animation will not work for this particular use case. Using setAlpha()
is the only way to get the desired results.
You will have to put this together with a RecyclerView OnScrollListener
This answer should help you with that.
It looks like the hardest part will be determining exactly what position you are at in the scrolling, See this question.
General code structure for OnScrollListener
, you will probably need to use trial and error to get the alpha values dialed in to where you want it:
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;
}
}
});