如何在'fragment'中找到listview

Leo*_*ong 4 android fragment

我有一个片段,发送请求到服务器并下载json,然后将其解析为listview,不知怎的,我无法正确到达视图.下面是我的应用程序的一部分,这是我第一次触及列表视图与片段,为某些原因我只允许使用Fragment所以我选择' setAdapter'而不是' setListAdapter'作为我的适配器

myfragment.java

 public class gallery extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View myFragmentView = inflater.inflate(R.layout.tab_frag2_layout,
                    container, false);
            return myFragmentView;
        }

    public void onActivityCreated(Bundle savedInstanceState) {
    .........
    .........
    .........
    setAdapter(colorAdapter);

    }
Run Code Online (Sandbox Code Playgroud)

layout.tab_frag2_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="#ffffff">

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/list_padding"
    android:paddingRight="@dimen/list_padding"
    android:tag="listf" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我的期望是用

MyListView = (ListView)myFragmentView.findViewById(R.id.list);

得到我的观点,但它不会那样工作......现在我只想得到我的列表视图并申请

MyListView.setAdapter(colorAdapter)

任何帮助将不胜感激,谢谢

Cal*_*vin 8

选项1:由于您的片段布局只包含一个简单的ListView.考虑使用

公共类库扩展了ListFragment

然后,您可以使用此代码获取列表视图.

myFragmentView.getListView()

选项2:正如Nickolaus所提到的,如果你想使用findViewById,你需要一个自定义id.

机器人:ID = "@ + ID/ListView1的"