Android 如何在';碎片';

Android 如何在';碎片';,android,fragment,Android,Fragment,我有一个片段,它向服务器发送请求并下载json,然后将其解析为listview,不知何故,我无法正确访问该视图。下面是我应用程序的一些部分,这是我第一次接触到带有片段的listview,出于某种原因,我只允许使用Fragment,因此我选择了“setAdapter”而不是“setListAdapter”作为我的适配器 myfragment.java public class gallery extends Fragment { public View onCreateView(Lay

我有一个片段,它向服务器发送请求并下载json,然后将其解析为listview,不知何故,我无法正确访问该视图。下面是我应用程序的一些部分,这是我第一次接触到带有片段的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);

    }
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>

我的期望是使用

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

来了解我的观点,但不是那样的。。。 现在我只想获取我的listview并应用它

MyListView.setAdapter(colorAdapter)
将其


如果您不想使用ListFragment,您需要添加一个自定义id(android:id=“@+id/custom_id”),然后您可以使用findViewById查找ListView

选项1:因为您的片段布局只包含一个简单的ListView。 考虑使用

公共类库扩展了ListFragment

然后可以使用此代码获取listview

myFragmentView.getListView()

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

android:id=“@+id/listview1”


你使用ListFragment吗?就像在活动中有ListActivities的片段一样,你有一个ListFragment。你的意思是唯一的方法是exends ListFragment来完成这项工作吗?这是一般的方法,我不确定你是否可以用其他方法来完成Android:id=“+@id/my_custom_id”我做错了吗?eclipse给了我一个字符串类型errorandroid:id=“@+id/custom_id”感谢您在android上分享我的新东西,它可以工作=)选择了第二个选项