我有一个自定义DialogFragment,它具有自己的RecyclerView,并且由于某种原因,除非在onCreate中执行适配器/ recyclerView逻辑,否则不会填充数据。如果在onCreateViewonViewCreated中调用它,则什么也不会发生,这是我希望所有这些逻辑发生的地方。这是在onCreate中工作的版本:

@Override public void onCreate(@Nullable Bundle savedInstanceState) {
    root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);

    ButterKnife.bind(this, root);

    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

}


这是我在onCreateView中的尝试:

@Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    root = (ViewGroup) inflater.inflate(R.layout.dialog_content, container, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
}


我也尝试在onCreateView中这样初始化root:root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);
但是没有骰子。

有谁知道这可能是什么原因?我也尝试在onViewCreated中添加相同的代码,但同样,没有运气。

PS-我还尝试在设置数据后添加adapter.notifyDataSetChanged(),也尝试在rv.setData之后添加。

最佳答案

请执行下列操作:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    root = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content, null, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

    return new AlertDialog.Builder(getActivity())
        .setView(root)
        .show();
}

10-08 19:10