Int*_*der 5 java android gridview
我在使用时在片段中出现了空指针异常Gridview
。我的代码是
public class HomeFragment extends Fragment {
GridView grid;
String[] web = { "Bata", "Service", "puma", "Hush" };
int[] imageId = { R.drawable.shoesmall, R.drawable.shoe1, R.drawable.shoe3,
R.drawable.shoe4 };
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_home, container);
CustomGrid adapter = new CustomGrid(getActivity().getApplicationContext(), web, imageId);
grid = (GridView) getView().findViewById(R.id.gridview);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity().getApplicationContext(),
"You Clicked at " + web[+position], Toast.LENGTH_SHORT)
.show();
}
});
return rootView;
}
}
Run Code Online (Sandbox Code Playgroud)
谁能指导它为什么要包装?我通常不使用片段。
你的getView()
值为空,因为视图尚未创建,所以更改
grid = (GridView) getView().findViewById(R.id.gridview);
Run Code Online (Sandbox Code Playgroud)
到
grid = (GridView) rootView.findViewById(R.id.gridview);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
294 次 |
最近记录: |