我一直在尝试重新设置 ImageView 的大小。 我正在使用自定义适配器。
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_item, null);
}
thumb = (ImageView) row.findViewById(R.id.bookThumb);
当我使用 ImageView thumb = (ImageView) row.findViewById(R.id.bookThumb);在自定义适配器中,它工作得很好,但因为它循环遍历每一行,所以滚动速度非常慢。
所以...我现在正在尝试获取 thumb = (ImageView) row.findViewById(R.id.bookThumb);从我的主要 Activity 中设置它的大小,但我得到 Null,因此应用程序强制关闭。
尝试过:
LinearLayout layout = (LinearLayout) findViewById(R.id.gridLayout);
ImageView thumbRow = (ImageView)layout.findViewById(R.id.bookThumb);
还试过:
// gv is the gridview (R.id.gridview)
ImageView thumbRow = (ImageView)gv.findViewById(R.id.bookThumb);
始终为空。
感谢任何帮助!感觉我错过了一些愚蠢的东西:)
最佳答案
我认为问题源于两个地方。
首先解决原始问题。由于 findViewById 调用,您的适配器速度很慢。您使用了回收 View ,这很好,但是您仍然遍历缩略图的 View 。有一种技术,非正式地称为 ViewHolder,它基本上使其更像是直接调用。
因此,与其仅仅使用回收 View 作为开始填充数据的地方,还可以为其附加一些结构,以便您可以预取要操作的元素
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_item, null);
row.setTag(row.findViewById(R.id.bookThumb));
}
thumb = (ImageView) row.getTag();
这里直接通过变量调用,没有遍历。这应该快得多。
同样是第二个问题,NullPointerExcepton。
我认为这是 id 的模糊性以及您在主要 Activity 中调用 findViewById 的点。你不能在你的 mainActivity 中真正做得好,特别是如果涉及滚动,因为你必须拦截在适配器 View 中呈现的调用。大多数回调已经在主线程上,所以两件事不能在该线程上同时发生。
因此在您调用 findViewById() 时,适配器可能还没有运行并将该 View 附加到层次结构。如果是这样,它可能还没有完成对它的操纵。
在解决第二个问题之前,我会尝试加速您的适配器,因为我不确定是否有可能在不完全放弃使用适配器 View 的情况下安全或准确地执行此操作。
关于Android:ImageView 的 findViewById(自定义适配器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5369252/