我应该使用View Holder图案作为我的适配器吗?

当我创建一个类extends BaseAdapter ,我收到一条警告消息

Unconditional layout inflation from view adapter: Should use View Holder pattern (use recycled view passed into this method as the second parameter) for smoother scrolling

我是否需要像这个建议一样更改我的代码? 我的所有代码都运行得很顺利,是否有necessary更改代码以使用最新样式执行updata代码? 或者只需要添加@SuppressLint({ "ViewHolder", "InflateParams" })

我的适配器

 public View getView(int position, View convertView, ViewGroup parent) { View v = inflater.inflate(R.layout.list_item, null); TextView merchant_type = (TextView) v.findViewById(R.id.merchant_type); TextView merchant_name = (TextView) v.findViewById(R.id.merchant_name); TextView merchant_location = (TextView) v.findViewById(R.id.merchant_location); VoucherBean obj = (VoucherBean) getItem(position); merchant_type.setText(obj.getMerchantType()); merchant_name.setText(obj.getMerchantName()); merchant_location.setText(obj.getMerchantLocation()); return v; } 

如果你想按照上面推荐的警告更改我的代码,就像我的代码稍后一样? 对不起,如果我的问题对初学者来说太基础了

如果您在列表视图中有更多数据,那么您应该使用回收,因为它还可以改善滚动和性能。 如果您在适配器中使用视图持有者,则代码如下所示。

你的ViewHolder看起来像

 public class ViewHolder { public TextView merchant_type; public TextView merchant_name; public TextView merchant_location; } 

和你的getView方法

  View vi = convertView; ViewHolder holder; if (convertView == null) { vi = inflater.inflate(R.layout.list_item, null); holder = new ViewHolder(); holder.merchant_type = (TextView) vi.findViewById(R.id.merchant_type); holder.merchant_name = (TextView) vi.findViewById(R.id.merchant_name); holder.merchant_location = (TextView) vi.findViewById(R.id.merchant_location); vi.setTag(holder); } else holder = (ViewHolder) vi.getTag(); // now set your text view here like holder.merchant_name.setText("Bla Bla Bla"); // return your view return vi; 

View Holder模式旨在使您的代码更易于阅读和维护。 如果你看一下标准的ViewHolder,你会发现它是一个基本上你在你的getView中做的事情的类:

 private static class ExampleViewHolder{ TextView merchant_type; TextView merchant_name; TextView merchant_location; public ExampleViewHolder(View view){ merchant_type = (TextView) v.findViewById(R.id.merchant_type); merchant_name = (TextView) v.findViewById(R.id.merchant_name); merchant_location = (TextView) v.findViewById(R.id.merchant_location); } } 

然后在你的getView方法中,你会得到这样的视图:

 ExampleViewHolder holder = new ExampleViewHolder(view); view.setTag(holder); 

让它们和更新的apis强制使用这种模式是很好的,但是正如你可以从代码中看到的那样,它除了可读性和易维护性之外没有太大变化。

然而! 您缺少getView方法的一个重要部分,很可能是警告的原因。

listview将回收视图,并将它们返回给适配器,以便每次都不必对同一视图进行充气。 节省资源和大量内存,而您没有利用listView这个非常重要的方面。

你看,回收视图的方式是将之前膨胀的旧视图通过convertView传递回适配器,因此如果convertView不为null,则可以确定它正在使用的膨胀布局。 所以使用它而不是膨胀一个新的:

 View view = convertView; ExampleViewHolder holder; if(view == null){//means convertView is also null view = inflater.inflate(yourlayout, parent, false); holder = new ExampleViewHolder(view); view.setTag(holder); }else{ holder = (ExampleViewHolder) view.getTag(); }