'Calling variables inside ViewHolder through Activity

In my RecyclerViewAdapter, part of my codes are below:

@Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.music_item_lists, parent, false);
        return new ViewHolder(v);
    }
    class ViewHolder extends RecyclerView.ViewHolder {
       
        EqualizerView equalizerView, equalizerr;
        CardView image_card;

        ViewHolder(View itemView) {
            super(itemView);
            
            equalizerView = itemView.findViewById(R.id.mini_eq_view);
            image_card = itemView.findViewById(R.id.main_card_view_play);
            equalizerView.stopBars();
            equalizerView.setVisibility(View.GONE);
        }
    }

Then in MainActivity, part of the codes are below

@Override
    public void playSongComplete() {
        Log.d("complete", "Playing song is complete: ");

    }

What I want to do is, if playing song is complete, I want to call

equalizerView.stopBars();
equalizerView.setVisibility(View.GONE);

from inside method playingSongComplete(). Is there any way to do that?



Solution 1:[1]

create a function inside your adapter like

void stopEqualiser(){
   equalizerView.stopBars();
   equalizerView.setVisibility(View.GONE);
}

then in the activity when music complete

@Override
public void playSongComplete() {
    
  // your recycler adapter
    adapter.stopEqualiser();

}

Solution 2:[2]

As far as I know, we cannot access variables inside viewholder from an activity. What we can do however is modify the data of the adapter and notify the adapter about the changed data. We can then handle the data change inside the onBindViewHolder method

you can create a boolean variable called isSongComplete with initial value false inside the adapter, then create function inside your adapter like this

void setComplete(){
    isSongComplete = true;
    notifyDataSetChanged();
}

and in your onBindViewHolder method inside your viewholder class

@Override 
public void onBindViewHolder(ViewHolder holder, int position) {
    if (isSongComplete) {
        equalizerView.stopBars();
        equalizerView.setVisibility(View.GONE);   
    }
}

then in your MainActivity

@Override
public void playSongComplete() {
    Log.d("complete", "Playing song is complete: ");
    adapter.setComplete();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Flying Dutchman
Solution 2 dito cesartista