循环器视图实例在屏幕旋转时保留

时间:2017-10-15 08:19:23

标签: java android android-recyclerview

我正在使用无UI片段来保存ViewModel类的状态。 ViewModel类的状态按预期保留。 保留片段:

public class LoveMatchActivityRetainFragment extends Fragment {

private LoveMatchViewModel loveMatchViewModel;

@Inject
public LoveMatchActivityRetainFragment() {}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
}

public void retainViewModel(LoveMatchViewModel loveMatchViewModel) {
    Log.e("df", loveMatchViewModel + " ");
    this.loveMatchViewModel = loveMatchViewModel;
}

public LoveMatchViewModel getViewModel() {
    return this.loveMatchViewModel;
}

}

活动类:

@Override
protected void onCreate(Bundle savedInstanceState) {

     if (getSupportFragmentManager().findFragmentByTag("my_fragment") == null) {
        mLoveMatchActivityRetainFragment = new LoveMatchActivityRetainFragment();
        getSupportFragmentManager().beginTransaction().add(mLoveMatchActivityRetainFragment, "my_fragment").commit();

    } else {
        mLoveMatchActivityRetainFragment = (LoveMatchActivityRetainFragment) getSupportFragmentManager().findFragmentByTag("my_fragment");
    }

    mLoveMatchActivityRetainFragment.getViewModel();

    if (mLoveMatchActivityRetainFragment.getViewModel() != null) mViewModel = mLoveMatchActivityRetainFragment.getViewModel();

    bindingRecyclerViewAdapter = new BindingRecyclerViewAdapter<>(null);
    mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
    mBinding.rcv.setAdapter(bindingRecyclerViewAdapter);
    Log.e(debugTag, bindingRecyclerViewAdapter + " adapter");
}



@Override
protected void onDestroy() {
    super.onDestroy();
    dismissDialog();
    mLoveMatchActivityRetainFragment.retainViewModel(mViewModel);
    mLoveMatchActivityRetainFragment = null;
}

我有一个RecyclerView来填充数据列表。我初始化onCreate()内的RecyclerView以摆脱没有附加适配器,跳过布局&#39;错误。此外,我还有一个功能,只要我从网络获取数据,就可以使用真实数据填充RecyclerView。

private void initializeRcView(final ArrayList<PetObj> data) {
    bindingRecyclerViewAdapter.setItems(data);
    Log.e(debugTag, this.bindingRecyclerViewAdapter + " adapter here: "+this);
    bindingRecyclerViewAdapter.notifyDataSetChanged();
 }

第一次加载活动并从网络RecyclerView获取数据按预期填充。问题是旋转屏幕时。一世 在onCreate()initializeRcView()方法中记录了Activity和RecyclerView适配器的实例。每次都在onCreate()内创建两个新实例,但在initializeRcView()内,实例始终保持不变。我从保留的片段中删除了setRetainInstance(true),并在轮换更改时正确填充了RecyclerView。任何人都可以解决这个问题吗?为什么实例在initializeRcView()内保持不变?

0 个答案:

没有答案