【问题标题】:Populate a Listview from another Fragment从另一个 Fragment 填充 Listview
【发布时间】:2012-07-26 11:50:51
【问题描述】:

我正在尝试制作一个选项卡式 Android 应用。两个选项卡都是列表视图。第一个选项卡从 RSS Feed 获取帖子。第二个标签按类别显示它们。

问题是我想从第一个选项卡的片段中填充第二个选项卡中的列表视图。

我的第一个片段的代码是:

public class PostsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.posts_fragment, container, false);
    return view;
}

...
...
...

// Populate the "posts_fragment.xml" with Posts 
public void populate_postview() {
    ListView lv1;

    lv1 = (ListView)getView().findViewById(R.id.postlist);
    lv1.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1 , arrays.PsychoTitle));
    lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            ...             
        }
    });

// Populate the "categories_fragment.xml" with Categories
public void populate_catview() {
    ListView lv2;

    lv2 = (ListView)getView().findViewById(R.id.catList);
    lv2.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1 , arrays.PsychoCategories));
}

这里的问题是populate_catview() 中的catList 是“categories_fragment.xml”的一部分,但使用getView() 返回的当前布局是“posts_fragment.xml”。

那么如何在第二个片段中填充项目列表呢?

【问题讨论】:

    标签: android listview arraylist android-fragments


    【解决方案1】:

    在这里查看我的答案Call functions of Activities Belonging to a Fragment 它足以解释它。您不应该直接调用另一个片段的方法。片段应该是自包含的。创建一个到活动的接口,然后使用第二个片段中的数据调用一个方法。

    【讨论】:

      【解决方案2】:

      假设两个片段具有相同的父 Activity,一种解决方案是将支持列表的数据保存在父 Activity 中。然后,当用户点击任一选项卡时,相应的片段会检索数据并相应地填充列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 2014-04-18
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多