gpt4 book ai didi

android - 在 Fragment 中创建图像的 GridView

转载 作者:行者123 更新时间:2023-11-29 19:46:04 31 4
gpt4 key购买 nike

我正在尝试在 fragment 中创建 GridView 。我已经实现了适配器类和相应的覆盖方法。但是在运行时它会在行中抛出异常:

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

}

最佳答案

改变这一行

GridView gridView = (GridView) (getActivity().findViewById(R.id.ocrgridview));

GridView gridView = (GridView) v.findViewById(R.id.ocrgridview); //Note "v" not activity

关于android - 在 Fragment 中创建图像的 GridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37656555/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com