2013-06-23 61 views
0

MainFragment類後:的NullPointerException甚至膨脹所述片段

public class FragmentMain extends Fragment { 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_main, container, false); 
     GridView gridview = (GridView)getActivity().findViewById(R.id.grid_view); 
     gridview.setAdapter(new ImageAdapter(getActivity(), thumbnails)); //gridview is null!!! 

     getActivity().setTitle(title); 
     return view; 
    } 
} 

fragment_main.xml佈局(gridview的甚至充氣後爲空)

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

</GridView> 

回答

2
GridView gridview = (GridView)getActivity().findViewById(R.id.grid_view); 

必須使用圖中未getActivity()到致電findViewById

GridView gridview = (GridView)view.findViewById(R.id.grid_view); 

因爲您的GridView屬於Layout您正在充氣