TL;DR:我无法区分RecyclerView
' 调用onBindViewHolder
何时回收 aView
或替换Fragment
.
我确实花了很多时间在这里寻找答案,但最终没有任何效果。它所做的只是告诉我答案可能是在 using 中savedInstanceState
,但我没有成功使用它。
结构 :
- 主要片段
- 主视图
- 切换片段按钮
在里面MainView
是一个FrameLayout
,用来装一个Fragment
。
第一个Fragment
无关紧要,但第二个Fragment
是 an OverviewFragment
,其结构为:
- 概述片段
- 回收站视图
- 自定义项目视图
- 文本视图
- 更改文本颜色按钮
- 删除项目按钮
- ...
- 自定义项目视图
- 添加项目按钮
- 回收站视图
我正在使用 aRecyclerView
因为列表需要是水平的,这是我发现的最简单的方法。
期望的行为:
我希望当我单击按钮两次(更改片段然后返回它)时保持颜色更改,而不是当我从列表中删除项目然后再次添加它时。
问题 :
颜色要么一直保存,要么从不保存。onBindViewHolder
在's Adapter 中使用RecyclerView
来设置文本颜色不允许我区分绑定是来自片段替换(我将恢复更改的颜色)还是视图回收(我不会恢复它)
代码 :
'调用SwitchFragmentButton
'方法OnClickListener
MainView
void switchFragment(Fragment fragment) {
FragmentManager fm = mainFragment.getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.mainView_fragment_slot, fragment);
ft.commit();
}
以下是颜色的管理方式(简化):
public class CustomItemView extends FrameLayout {
private TextView textView;
private int color;
/* other attributes */
public CustomItemView(/* any default constructor */) {
super(/* args */);
init();
}
private void init() {
inflate(getContext, R.layout.custom_item_view, this);
textView = (TextView) findViewById(R.id.customItemView_text_view);
ChangeTextColorButton ctcButton = /* ... */;
/* other views */
ctcButton.setOnClickListener(new OnClickListener() {
public void onClick() {
setColor(getColorWithDialogAndAll());
}
}
resetColor();
}
public void resetColor() {
setColor(0xff0000ff);
}
public void setColor(int color) {
this.color = color;
textView.setTextColor(color);
}
/* other methods */
}
这是RecyclerView
的Adapter
定义:
public class MyAdapter extends RecyclerView.Adapter {
private List<MyItem> myItemList = new LinkedList<>();
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
MyViewHolder viewHolder = (MyViewHolder) holder;
//this is called in both situations
viewHolder.customItemView.resetColor();
}
/* other methods */
private class MyViewHolder extends RecyclerView.ViewHolder {
CustomItemView cutsomItemView;
/* constructor, calling super() and setting the attribute */
}
}
MyItem
这是CustomItemView的核心项目(每个MyItem都有它的CustomItemView,每个CustomItemView都有它的MyItem)
备注:
minSdkVersion
: 19。
编辑 :
感谢@goldenb,问题已经缩小,出现了两种解决方案。
解决方案 1:
不要替换片段,而是将它们全部添加,然后显示/隐藏它们。
void switchFragment(Fragment fragment) {
FragmentManager fm = mainFragment.getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.hide(currentFragment);
ft.show(R.id.mainView_fragment_slot, fragment);
ft.commit();
currentFragment = fragment;
}
该解决方案以某种方式有效,但并不是真正解决问题。它避免删除Fragments
,所以状态被保留。
但是,我的问题是关于如何保存然后恢复Fragment
的状态,所以我不能接受这个作为答案。
解决方案 2:
覆盖OverviewFragment#onPause
以保存状态,并将其恢复为OverviewFragment#onCreate
.
这个解决方案似乎是合理的,我目前正在探索它。然而,它需要在我的项目中进行一些重组才能将数据从 重新定位CustomItemView
到MyAdapter
,因此需要一些时间。