我有一个名为 TestListAdpater 的 ArrayAdapter 子类,其构造函数如下:
public TestListAdapter(Context context,int viewResourceId, List<TestObjects>
objects) {
super(context, viewResourceId, objects);
iHostViewID = viewResourceId;
}
其 getView 方法如下:
@Override
public View getView(int pos, View convertView, ViewGroup parent){
View itemView = convertView;
LayoutInflater inflater =
(LayoutInflater)hContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(iHostViewID, null);
TextView testTV =
(TextView)itemView.findViewById(R.id.widget_listitem_test_TV);
testTV.setText("Testing...");
}
然后我将这些测试项中的 20 个添加到 TestListAdapter,足以让我可以上下滚动浏览它们。经过几个循环,所有这些都向下滚动到底部,然后再回到顶部,我收到一个 OutOfMemory 异常,应用程序崩溃了。我的问题是三个:
为什么首先会发生这种情况? ArrayAdapter 不会保留已经在 RAM 中呈现的 View ,以便在为至少已显示一次的 View 调用 getView() 时不必重新分配任何内容吗?
无论用户滚动 ListView 的频率如何,我如何才能绝对防止这种情况发生?
LayoutInflater::inflate() 是否总是分配新资源?
Android 的 Adapter 的源代码让我有一种感觉接口(interface),问题是由我总是在 getView() 中膨胀 View 引起的; Adapter 的评论声称参数 convertView 是“如果可能,要重用的旧 View ”。我对自定义 ArrayAdapter 的实际用例需要覆盖 getView(),那么我如何实现 Android 的默认 ArrayAdapter 显然执行的可重用性检查? (粗略查看后,我没有在 ArrayAdapter 的来源中看到任何此类检查)
最佳答案
试试这个:
private LayoutInflater mInflater;
Context mContext;
public TestListAdapter(Context context,int viewResourceId, List<TestObjects>
objects) {
super(context, viewResourceId, objects);
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
this.iHostViewID = viewResourceId;
}
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
CollectHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(iHostViewID, null);
holder = new CollectHolder(convertView);
convertView.setTag(holder);
} else {
holder = (CollectHolder) convertView.getTag();
}
holder.testTV.setText("Testing...");
return convertView;
}
class CollectHolder {
TextView testTV;
public CollectHolder(View root) {
this.testTV = (TextView) root
.findViewById(R.id.widget_listitem_test_TV);
}
}
关于java - Android ArrayAdapter 导致 OutOfMemoryException (Content is only a TextView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506614/