我正在尝试在片段中创建网格视图。我已经实现了适配器类和相应的overriden方法。但是在运行它时会抛出异常:
gridView.setOnItemClickListener (this);
声明gridView对象是一个NULL指针。
这是我的代码(非常类似于Google Sample):
public static class OcrOverrideFragment extends Fragment implements AdapterView.OnItemClickListener {
// The Adaptor Class for the grid view
public class ImageAdaptor extends BaseAdapter{
private Context mContext;
public ImageAdaptor (Context c)
{
mContext = c;
}
public long getItemId(int position) {
return (long) position;
}
public Object getItem(int position) {
return null;
}
public int getCount (){
try
{
String[] f = mContext.getAssets().list("OcrSampleImages");
return f.length;
}
catch (IOException e)
{
LogUtil.d (TAG,"OCR_OVERRIDE gave " + e);
}
return 0;
}
// For each of the items in the grid, this method will be called
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
try
{
String[] f = mContext.getAssets().list("OcrSampleImages");
if (convertView == null) {
imageView = new ImageView(getContext());
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView) convertView;
}
// Setting the appropriate image for each gird item
imageView.setImageBitmap(getBitmapFromAsset("OcrSampleImages"+System.getProperty("file.separator")+f[position]));
}
catch (IOException e)
{
LogUtil.d (TAG,"OCR_OVERRIDE gave " + e);
}
return imageView;
}
} // End Of ImageAdaptor Class
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.ocr_override, container, false);
GridView gridView = (GridView) (getActivity().findViewById(R.id.ocrgridview));
gridView.setAdapter(new ImageAdaptor(v.getContext()));
gridView.setOnItemClickListener (this);
return v;
}
@Override
public void onItemClick (AdapterView<?> adaptorView,View v,int i,long l)
{
// Implementation details unncessary
}
答案 0 :(得分:1)
更改此行
GridView gridView = (GridView) (getActivity().findViewById(R.id.ocrgridview));
要
GridView gridView = (GridView) v.findViewById(R.id.ocrgridview); //Note "v" not activity
答案 1 :(得分:1)
getActivity()
返回此片段当前与之关联的活动。
但是
查看v
在布局文件中获取 v
的引用。
这就是为什么我们称第二种方法而不是第一种方法。 您可以访问以下以获得更好的答案
<强> Difference between getActivity() and view in Fragment 强>