【发布时间】:2019-05-08 15:54:27
【问题描述】:
我在工具栏中有一个Switch 按钮,在RecyclerView 中有两个TextViews。
我想根据Switch 的状态管理RecyclerView 中TextViews 之一的可见性。
我已将 OnCheckedChangeListener 添加到 Switch 并在此处设置布尔值 FLAG 到 TRUE 的 FALSE。这个FLAG 值是在Adapter 的onBindViewHolder(-,-) 方法中读取的,我根据FLAG 将视图可见性设置为VISIBLE/GONE。
在 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()
}
});
...
}
在适配器中:
public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
if (((MainActivity) mContext).isSwitchFlag()) {
viewHolder.textView.setVisibility(View.VISIBLE);
...
}
如何在Toolbar 中的任何事件中显示/隐藏RecyclerView 中的视图?
【问题讨论】:
-
为适配器中的开关添加一个变量。为该变量添加 getter(如果需要)和 setter 方法,在 setter 添加 adapter.notifyDataSetChanged(); 并在 setOnCheckedChangeListener adapter.setSwitch(true); 中添加新行或 adapter.setSwitch(true); 根据您的要求。
-
嗨@NikulVadher 我如何初始化适配器类中的开关变量? Switch 的布局在 MainActivity 中膨胀,而 Adapter 的布局用于 RecyclerView。
-
@Sabdeep Yohans 您可以在 Adapter 类的构造函数中初始化默认情况下您可以将 false 设置为 switch 的默认值,但如果在 xml 中更改了 switch 默认值 android:checked="true " 然后你可以用 true 初始化
-
好的,试试看。谢谢。
-
让我知道它是否有效,否则我将分享有关此的代码。
标签: android android-recyclerview android-switch