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

Ber*_*ris 2 java android

当我创建一个类时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;
}
Run Code Online (Sandbox Code Playgroud)

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

Dro*_*Dev 5

如果您在列表视图中有更多数据,那么您应该使用回收,因为它还可以改善滚动和性能.如果您在适配器中使用视图持有者,这里的代码就像.

你的ViewHolder看起来像

public  class ViewHolder {

        public TextView merchant_type;
        public TextView merchant_name;
        public TextView merchant_location;

    }
Run Code Online (Sandbox Code Playgroud)

和你的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;
Run Code Online (Sandbox Code Playgroud)