Search code examples
androidandroid-recyclerviewdata-bindingandroid-adapterandroid-databinding

How to get specific position view in RecyclerView?


I have a recyclerView. One of recyclerView items has an onClick method. In this method, I setVisibility for one Item to Visible(default is gone), also get the position and add it to an arrayList.

onClick :

public void onClickImageView(ImageView imageView, int position) {
    imageView.setVisibility(View.VISIBLE);
    positionArrayList.add(position);
}

Before i go to another activity, I want to the ImageView visibility be reset to default (gone) so I use an interface to send positionArrayList to the recyclerView activity to get views by position and reset ImageViews to default.

Interface :

public interface RecyclerViewMainActivityImp {
    void resetImageViewToDefault(ArrayList<Integer> positionArrayList);
}

Where I use interface method in adapter :

public void OnClickNextActivity() {
    Intent intent = new Intent();
    intent.setClass(context, ClassActivity.class);
    context.startActivity(intent);
    recyclerViewInterface.resetImageViewToDefault(positionArrayList);
}

Activity :

@Override
public void resetImageViewToDefault(ArrayList<Integer> positionArrayList) {
    for (int position = 0; position < positionArrayList.size(); position++) {
        View row = binding.recyclerView.getLayoutManager().findViewByPosition(positionArrayList.get(position));
        ImageView imageView = row.findViewById(R.id.imageView);
        imageView.setVisibility(View.GONE);    
    }
}

When i scroll the recyclerView, and if some items are not in view anymore their views going to null so some positions in positionArrayList no longer have their view.

My problem is some views are null after scrolling and I don't know how to get access to them.

I searched on google and found some solutions but I could not solve my problem

Note : I have used data binding


Solution

  • there's workaround you can try for this,

    create a function in your activity

    function void updateRecyclerView(position){
       yourArrayListForVisibility.set(position,'hide');
       mAdapter.notifyDataSetChanged();
    }
    
    
    @Override
    public void onResume(){
        super.onResume();
        mAdapter.notifyDataSetChanged();
    
    }
    

    call this function in your adapter before intent and in your adapter check for this arraylist value to hide or show content, always set default value to 'yourArrayListForVisibility' for every position