1

我已经在我的 xml 文件中构建了一个 GridView,现在我想将它填充到一个 Fragment 类中。(此 Fragment 类使用该布局)

用户主页.xml

<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/home_gridview"
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:layout_below="@+id/user_avatar"
android:paddingTop="16dp"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />

public class UserHomeFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    return inflater.inflate(R.layout.userhome, container, false);

}

我真的不知道如何拿走我的“home_gridview”,我尝试了一切,但没有奏效!我需要这个,因为我想在我的操作栏选项卡之一中使用它。你能帮我一些代码吗?谢谢你们!

4

1 回答 1

2

像这样包裹你的GridView内部LinearLayout(或其他布局):

<LinearLayout 
GridView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/home_layout"
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:orientation="vertical">
    <GridView android:id="@+id/home_gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_below="@+id/user_avatar"
    android:paddingTop="16dp"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />
</LinearLayout>

现在onCreateView找到你GridView的ID:

public class UserHomeFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view =  inflater.inflate(R.layout.userhome, container, false);
    GridView gridView = (GridView) view.findViewById(R.id.home_gridview);//must be your R not android.R
    //use your grid view

   return view;

}
于 2012-07-15T17:09:31.153 回答