问题
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