设置listAdapter后更新片段视图

时间:2014-06-30 07:02:37

标签: android android-activity android-fragments

我正在将现有活动(SherlockActivity)转换为片段(SherlockListFragment)以使用制表符。

片段在创建时返回onCreateView,并使用以下代码。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
     /** Creating array adapter to set data in listview */
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);

    /** Setting the array adapter to the listview */
    setListAdapter(adapter);

    return super.onCreateView(inflater, container, savedInstanceState);

}

这样可以正常工作,但正如我在我的活动中所做的那样,我想在从服务器上取出后用自己的内容更新列表视图。

ListView listContent = (ListView) getView().findViewById(R.id.contentlist);    
listContent.setAdapter(myAdapter);

无论我到目前为止研究过什么,我都是通过活动获取listview并将我的适配器设置为它,但这对片段视图没有影响并且它保持不变。

问题是:如何从onCreateView外部更新listView?

2 个答案:

答案 0 :(得分:0)

首先,将listview设为全局变量。然后在onCreateView函数上设置它的值:

ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_placelist, container, false);
    list = rootView.findViewById(/*your id*/)
     /** Creating array adapter to set data in listview */
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);

    /** Setting the array adapter to the listview */
   setListAdapter(adapter);

    return super.onCreateView(inflater, container, savedInstanceState);

}

//change your listview content here when refresh or something else
public void updateListView(){
    List l = /*fetch new data from server*/
    listAdapter.addAll(l);
    listAdapter.notifyDataSetChanged();
}

答案 1 :(得分:0)

    ListView list;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_placelist, container, false);
        list = rootView.findViewById(/*your id*/)
         /** Creating array adapter to set data in listview */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);

        /** Setting the array adapter to the listview */
       setListAdapter(adapter);

        return rootView;
}

从这里android版本必须是arraylist或字符串数​​组或hashmap