19

Using the following code within a RecyclerView.Adapter:

onBindViewHolder(VH holder, int position){
   holder.itemView.setAlpha(0.5f);
}

Alpha will not be shown the first time the item is shown. However, if you leave the screen and come back, Alpha is then accurately shown. The value is being set, but not displayed until it's shown again. Any ideas on how to get setAlpha() to take effect on first viewing.

Nic Capdevila
  • 1,495
  • 14
  • 27

3 Answers3

22

After further investigation, this happens only when using an animator (such as the android.support.v7.widget.DefaultItemAnimator ) which will clear whatever alpha is set for the view. You can use

RecyclerView.setItemAnimator(null);

and alpha will remain set

Nic Capdevila
  • 1,495
  • 14
  • 27
15

The RecyclerView default animator modifies the alpha set on the itemView set on the ViewHolder.

Wrap your itemView layout in a FrameLayout and modify the alpha of the children of the FrameLayoyt e.g:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id="@+id/system_modifies_my_alpha">

    <FrameLayout
        android:id="@+id/view_holder_bind_modifies_my_alpha">
        <!-- your children go here-->
    </FrameLayout>
</FrameLayout>
alexbirkett
  • 2,604
  • 2
  • 26
  • 30
1

Be sure to set setAlpha() during the creation of the Holder,

class ViewHolder extends RecyclerView.ViewHolder{
...
...
    public ViewHolder(View v){
        super(v);
        ...
        ...
        itemView.setAlpha(0.5f);
    }
}

not only inside onBindViewHolder()

onBindViewHolder(VH holder, int position){
   holder.itemView.setAlpha(0.5f);
}
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • 1
    https://developer.android.com/reference/android/view/View.html#setAlpha(float) Alpha is actually a float value between 0 and 1 – Nic Capdevila Dec 05 '16 at 17:38