Show/Hide views in RecyclerView on any event in Toolbar

六眼飞鱼酱① 提交于 2019-12-13 03:25:31

问题


I have a Switch button in toolbar and two TextViews in RecyclerView.

I want to manage the visibility of one of the TextViews in RecyclerView based on the state of Switch.

I have added OnCheckedChangeListener to the Switch and am setting a boolean FLAG to TRUE of FALSE here. This FLAG value is read in onBindViewHolder(-,-) method of the Adapter and I am setting the View visibility to VISIBLE/GONE based on the FLAG.

In MainActivity:

Switch switchView;
private boolean switchFlag;

public boolean isSwitchFlag() {
    return switchFlag;
}

public void setSwitchFlag(boolean switchFlag) {
    this.switchFlag = switchFlag;
}

protected void onCreate(Bundle savedInstanceState) {
    ...

    switchView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setSwitchFlag(isChecked);
            adapter.notifyDataSetChanged();
            //recyclerView.refreshDrawableState()        
        }
    });

    ...
}

In Adapter:

public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
    if (((MainActivity) mContext).isSwitchFlag()) {
        viewHolder.textView.setVisibility(View.VISIBLE);
        ...
    }

How do I manage to show/hide views in RecyclerView on any event in Toolbar?


回答1:


You better have a model that contains a field for text and a filed for handling visibility, then pass a list of this model to the recyclerView adapter. see below:

class ListItem {
   private String text;
   private boolean isVisible;
   //...put getter and seeter methods
}

In the OnCheckChangeListener you can change visibilty of items:

switchView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        for (ListItem item: mItems) {
            item.setVisiblity(isChecked);
        }
        adapter.notifyDataSetChanged();
    }
});

And finally, in onBindViewHolder section you can handle visibility of items.

public void onBindViewHolder(ViewHolder viewHolder, int position) {

    viewHolder.textView.setVisibility(mItems.get(position).isVisible() ? View.VISIBLE : View.GONE);
    viewHolder.textView.setText(mItems.get(position).getText());
    ...
}


来源:https://stackoverflow.com/questions/56035866/show-hide-views-in-recyclerview-on-any-event-in-toolbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!