【问题标题】:Showing ListFragment within Fragment在 Fragment 中显示 ListFragment
【发布时间】:2014-07-20 15:23:26
【问题描述】:

我正在尝试显示一个 ListFragment,它将显示另一个 Fragment 中的用户 cmets。出于测试目的,我使用父片段中的“onClick”方法调用 ListFragment。但是,我似乎无法显示 ListFragment,因为它没有“显示”方法。我的代码有什么明显的问题可以修复吗?

这是当我单击按钮以显示 ListFragment 时调用的方法。

private void showComments(JSONArray comments) {
    ListFragment newFragment = CommentsFragment.newInstance(comments);
}

这里是 ListFragment 本身。

public class CommentsFragment extends ListFragment {

public static CommentsFragment newInstance(JSONArray passedComments) {
    CommentsFragment f = new CommentsFragment();
    ArrayList<String> adapter = convertJSON(passedComments);
    Bundle args = new Bundle();
    args.putStringArrayList("adapter", adapter);
    f.setArguments(args);
    return f;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Bundle args = new Bundle();
    ArrayList<String> commentsArray = args.getStringArrayList("adapter");
    ArrayAdapter<String> commentsAdapter = new ArrayAdapter<String>(  
             getActivity(), R.layout.comments_list,  
             commentsArray);  
    setListAdapter(commentsAdapter);
}

【问题讨论】:

    标签: android android-fragments android-listview android-listfragment


    【解决方案1】:

    您必须使用 FragmentManager 提交 ListFragment,并且在 XML 中还有一个包含它的布局。

    首先将 FrameLayout 添加到您希望放置 ListFragment 的 XML 中,然后使用 getChildFragmentManager() 获取一个 FragmentManager,您可以使用它来放置 ListFragment。

    【讨论】:

    • 在 FrameLayout XML 中,我应该有 ListView 还是 TextView?
    • 它应该只是一个空的框架布局,其 ID 用作容器
    • 不幸的是,这只是将 listfragment 放在我当前的片段之上。
    • 你是在同一个 FrameLayout 中添加两个片段吗?
    • 所以,我可以通过废弃添加的 ListFragment 并在父片段中使用 ListView 来显示它。但是,此列表视图不会随屏幕滚动。
    【解决方案2】:

    这样试试

    private void showComments(JSONArray comments) {
            ListFragment newFragment = CommentsFragment.newInstance(comments);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(android.R.id.content, newFragment);
            fragmentTransaction.commit();
        }
    

    【讨论】:

    • R.id.content 标签有什么用?我已经用 `R.layout.cmets_list' 膨胀了 CommentsFragment。
    • @MilesPeele R.id.content 是保存视图的根布局。所以使用 R.layout.cmets_lis 代替 R.id.content。
    • 对,我就是这么想的。但是,当我这样做时,我得到了“没有找到 id 的视图”异常。
    • @MilesPeele 发布您的主要布局。
    • 现在可以了,谢谢。我不得不使用完全不同的方法来显示片段。现在我只需要弄清楚如何将对话框片段嵌入其父片段而不是显示为浮动窗口......有什么想法吗?
    猜你喜欢
    • 2013-10-11
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2016-07-28
    相关资源
    最近更新 更多