【问题标题】:Fragments inside RecyclerViewRecyclerView 中的 Fragment
【发布时间】:2020-03-10 20:43:23
【问题描述】:

首先:我对 android 还很陌生。这个项目可能高于我的工资等级,所以如果我问错了问题,至少你能理解。

我想将 TabLayout 与 ViewPager2 一起使用,每个页面将包含的视图由复杂的片段组成。每个页面都将具有相同的片段定义。据我所知,ViewPager2 依赖于 RecyclerView。我尝试为每个页面使用 LinearLayout,但一直收到引用 RecyclerView.Adapter 的错误。

我从另一个片段中创建 recyclerView:

recyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// use a linear layout manager
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
List<String> input = new ArrayList<>();
for (int i = 0; i < 5; i++) {
    input.add("Test" + i);
}// define an adapter
mAdapter = new SalinasAdapter(input, this);
recyclerView.setAdapter(mAdapter);

和 SalinasAdapter 的 onCreateViewHolder

public SalinasAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // create a new view
    View v = null;
    FragmentManager fm = mFragment.getChildFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    // Add the fragment but do not put it in a container
    ft.add(new RowFragment(), Integer.toString(mIndex));
    ft.commit();
    ft.commitNow();

    // Find the fragment from the fragment manager
    Fragment foo = fm.findFragmentByTag(Integer.toString(mIndex));
    mIndex++;

    // Keep track of the index in an ArrayList<String> so they can be removed from the 
    // FragmentManager when needed.
    // ToDo

    // Make sure it is mine
    if (foo instanceof RowFragment){
        v = foo.getView();
    }

    // Add the view to a ViewHolder
    ViewHolder vh = new ViewHolder(v);

    return vh;
}

据此,我假设真实视图被传递给 ViewHolder,它可以找到正确设置数据所需的所有元素。

完成后,应用程序会在崩溃前短暂显示五行。

我想我有两个问题: 这是看待这个问题的正确方法吗? 有没有办法调试,捕捉故障堆栈跟踪?

【问题讨论】:

  • 你有什么理由需要在这里使用 Fragments 吗? Fragment 有自己的生命周期回调,而 RecyclerView 的工作是回收视图,这肯定会导致以后的麻烦。
  • 尝试从 RecyclerView 适配器中管理 Fragment 生命周期是复杂且有些痛苦的。 ViewPager2 做了很多工作以使其正常工作。有关堆栈跟踪,请参阅Unfortunately MyApp has stopped. How can I solve this? 以获得特定于 Android 的建议,并参阅What is a stack trace, and how can I use it to debug my application errors? 了解获得它后的操作。
  • @Jacob Collins:我的标签布局页面中需要片段。我试图使用 RecyclerView 以外的东西,但它总是崩溃。有没有地方谈到在没有 RecyclerView 的情况下使用 ViewPager2?
  • "在没有 RecyclerView 的情况下使用 ViewPager2" - 这是不可能的,ViewPager2 完全基于 RecyclerView。这就像尝试使用 LinearLayout 而不使用 ViewGroup

标签: android android-recyclerview fragment


【解决方案1】:

(代表问题作者发布解决方案,将其移至答案空间)。

我通过添加:fragmentManager.executePendingTransactions() 而不是 commitNow() 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    相关资源
    最近更新 更多