当我运行我的 Activity 以显示下面的 GridView 时,它似乎卡在了位置 0。
您可以查看下面的日志,了解当 GridView 显示在屏幕上时发生的情况。这在第一次加载时工作正常,但当它滚动时,它似乎试图重用第一个位置 (0),即使它仍在使用中并因空指针异常而崩溃。
为什么要立即重用 View ?为什么它会认为 else 连续多次阻塞?是 Adapter 被扩展了 FrameLayout 的 CheckableButton 搞糊涂了吗?
谢谢!
public View getView(int position, View convertView, ViewGroup parent) {
CheckableButton checkableButton;
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ViewGroup.LayoutParams(175, 175));
checkableButton = new CheckableButton(mContext);
checkableButton.setLayoutParams(new GridView.LayoutParams(
GridView.LayoutParams.WRAP_CONTENT,
GridView.LayoutParams.WRAP_CONTENT));
checkableButton.addView(imageView);
Log.d("Initiated New View:", "" + position);
}
else {
checkableButton = (CheckableButton) convertView;
imageView = (ImageView) checkableButton.getChildAt(position);
Log.d("Reused View:", "" + position);
}
imageView.setImageBitmap(photos[position]);
return checkableButton;
}
这是 Log.d 读数
D/发起新观点:﹕0
D/重用 View ::0
D/重用 View ::0
D/重用 View ::0
D/发起新观点:﹕1
D/发起新观点:﹕ 2
D/发起新观点:﹕ 3
D/发起新观点:﹕ 4
D/发起新观点:﹕ 5
D/发起新观点:﹕ 6
D/发起新观点:﹕ 7
D/发起新观点:﹕ 8
D/发起新观点:﹕ 9
D/发起新观点:﹕0
D/重用 View ::0
D/重用 View ::0
D/重用 View ::0
D/重用 View ::0
D/重用 View ::0
最佳答案
getView 方法中的位置参数实际上是屏幕上显示的每个可见项目的索引。因此,例如,如果您的适配器中有 20 个项目,则滚动模式下的位置 arg 会在列表末尾变为 20。在您的实现中,checkableButton 只有一个 child ,因此当位置大于 checkableButton subview 计数时它会失败。尝试做这样的事情
imageView = (ImageView) checkableButton.getChildAt(0);
因为您的 imageView 是 checkableButton 的唯一 subview ,它使用 0 索引访问。
关于android - 滚动时 GridView 在 getView 方法中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32277897/