Target Target - 9 days ago 6
Android Question

Set Alfa on ImgeView Based on Position in Recycler Adapter

I have a RecyclerView and I am populating 4 imageView. My need is that when First Item is on top visible position the it must Alfa 1 and other items must be on 0.2f Alfa..

As I scroll my recycler view then, Item who comes on top position, it should be Set as Alfa 1. What I did..

My Adapter

@Override
public void onBindViewHolder(PageCircleIndiAdapter.ViewHolder holder, int position) {
final PageModels pageModels = pageList.get(position);
if (pageList.get(position) != null) {
holder.imageView.setImageResource(pageModels.resourceId);

}
if (position == 0) {
holder.rlyt.setAlpha(1f);
pageCircleIndicator.changeIndicator(position);
}

else if (position >firstVisible && position<lastVisible) {
holder.rlyt.setAlpha(1f);
pageCircleIndicator.changeIndicator(position);
} else if(position==pageList.size()-1){
holder.rlyt.setAlpha(1f);
pageCircleIndicator.changeIndicator(position);
}
else {
holder.rlyt.setAlpha(0.2f);
pageCircleIndicator.changeIndicator(position);
}
}


**My MainActivity Scroll Listener **

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();

int firstVisible = manager.findFirstVisibleItemPosition();
int lastVisible = manager.findLastVisibleItemPosition();
Log.i("TAG", "onScrolled: " + firstVisible);
Log.i("TAG", "Last Index: " + lastVisible);
pageAdapter.changeItem(firstVisible, lastVisible);

}

});

createIndicator();
pageAdapter.notifyDataSetChanged();
}

Answer

By default keep the item layout alfa 0.2f in your xml layout.

Now as you are passing first visible item position to adapter in addOnScrollListener using changeItem method. In adapter make a change like:

@Override
public void onBindViewHolder(PageCircleIndiAdapter.ViewHolder holder, int position) {
    final PageModels pageModels = pageList.get(position);
    if (pageList.get(position) != null) {
        holder.imageView.setImageResource(pageModels.resourceId);

    }
    if (position == 0 || position == firstVisible) {
        holder.rlyt.setAlpha(1f);
        pageCircleIndicator.changeIndicator(position);
    }else {
        holder.rlyt.setAlpha(0.2f);
        pageCircleIndicator.changeIndicator(position);
    }
}
Comments