Skip to content Skip to sidebar Skip to footer

How To Access View Inside Activity From Adapter In Android?

Does anyone knows how to access adapter imageView inside activity to hide the view. Please specify any example.

Solution 1:

I hope this will work for you.

By using SharedPreferences we can easily hide the view from activity or fragment.

Save flag in SharedPreferences i.e true from activity.

If you are using Recyclerview then in onBindViewHolder method check condition

if(flag==true){
    holder.yourView.setVisibility(View.GONE);
}else{
    holder.yourView.setVisibility(View.VISIBLE);
}

Solution 2:

Go to onBindViewHolder of the adapter and take the id of your imageview and code like this holder.mImgVw.setVisibility(View.GONE);


Solution 3:

You should not directly interact with the ImageView, instead you can use notifyItemChanged() to update the ImageView state in the Adapter. But, you need to slightly modify your Adapter code by adding a flag in your model data or using SparseBooleanArray as a mechanism to saving the ImageView state.

Here the example:

public class Adapter ... {
  private SparseBooleanArray mSelectedItems;
  private List<YourModel> mItems;

  public Adapter(List<YourModel> items) {

    mItems = items;
    mSelectedItems = new SparseBooleanArray();
  }

  ...
  public void onBindViewHolder(....) {
    int itemPosition = viewHolder.getAdapterPosition();
    YourModel item = items.get(itemPosition);

    boolean visible = mSelectedItems.get(itemPosition);   
    viewHolder.imageView.setVisibility(visible? View.VISIBLE: View.GONE);

    ...
  }

  public void setItemVisibilityByPosition(int position, boolean visible) {
    mSelectedItems.put(position, visible);
    notifyItemChanged(position);
  }

}

You can change the image visibility with:

 // Assume the mAdapter is your Adapter
 mAdapter.setItemVisibilityByPosition(5, true);

Post a Comment for "How To Access View Inside Activity From Adapter In Android?"