我正在使用 GridView 显示一些图像,但我遇到了问题,因为 onClickListener 不适用于第一张图像。我在 SO 上发现了其他一些有同样问题的问题,但我不喜欢他们的“正确答案”,因为他们中的大多数人都采用相同的方法:
基本上,每次调用 getview 时都实例化 View 。这对性能来说很糟糕,他们可能会在许多设备中面临内存不足的问题。
在我的例子中,我在 GridView 中显示位于 Assets 文件夹中子文件夹内的图像。
我的原始代码有“第一项”问题(实际上,我的原始代码实现了 viewholder 模式,但是这个代码更简单并且面临同样的问题):
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
AssetManager assetManager = _activity.getAssets();
InputStream assetIn = null;
try {
assetIn = assetManager.open(_assets_subdir + File.separator + _filePaths.get(position));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap image = BitmapFactory.decodeStream(assetIn);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
我解决问题的最终代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
AssetManager assetManager = _activity.getAssets();
InputStream assetIn = null;
try {
assetIn = assetManager.open(_assets_subdir + File.separator + _filePaths.get(position));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap image = BitmapFactory.decodeStream(assetIn);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
问题已解决,移动代码 imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
。
但是为什么?我不确定。
我在某处(在 SO 中)读到它可能是因为试图访问尚未膨胀的 View 而发生的,并且用户建议使用 getViewTreeObserver()
,但我尝试了这种方法并且无法解决问题。
因此,我决定对代码进行试错以查看可能存在瓶颈的位置并找到给定的解决方案。
有人知道为什么这样可以解决问题吗?
最佳答案
GridView extends from AbsListView -> GridView.LayoutParams 实际上是 AbsListView.LayoutParams,其中包括一些关于 View 类型和是否被回收的状态数据。
通过在每次调用 getView 时初始化一组新的布局参数(而不仅仅是在重新创建 View 时),您将丢失此状态数据。
我(目前)不确定为什么它只对网格中的第一项造成问题。
关于android - 为什么更改布局参数的设置位置可以解决我的 "OnClickListener not working for first item in GridView"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20437404/