多次调用视图

时间:2016-03-18 14:37:25

标签: android listview getview

以下是我的Adapter方法,

     public class StatusAdapter extends BaseAdapter {

    private Context mContext;
    private View view;
    private ViewHolder mViewHolder;
    private LayoutInflater layoutInflater;
    private ArrayList<ShipmentMasterDao> listForView;

    public StatusAdapter(Context mContext, ArrayList list) {
        super();
        mContext = mContext;
        listForView = list;
        layoutInflater = LayoutInflater.from(mContext);
    }


    @Override
    public int getCount() {
        return listForView.size();
    }

    @Override
    public Object getItem(int position) {
        return listForView.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    //Viewholder class to contain inflated xml views
    private class ViewHolder {
        private TextView mstatus, mDate;
        private ImageView image;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        view = convertView;

        if (convertView == null || mViewHolder != null) {
            //inflate the view for each row of listview
            view = layoutInflater.inflate(R.layout.status_progress, null);
            //ViewHolder object to contain myadapter.xml elements
            mViewHolder = new ViewHolder();
            mViewHolder.image = (ImageView) view.findViewById(R.id.progressIcon);
            mViewHolder.mDate = (TextView) view.findViewById(R.id.date);
            mViewHolder.mstatus = (TextView) view.findViewById(R.id.status);
            view.setTag(mViewHolder);

        } else {
            mViewHolder = (ViewHolder) view.getTag();

        }
        ShipmentMasterDao item = (ShipmentMasterDao) listForView.get(position);

        mViewHolder.mstatus.setText(item.getStatus());
        mViewHolder.mDate.setText(item.get_date());
        mViewHolder.mDate.setVisibility(View.VISIBLE);

        return view;
    }
}

在onViewCreated方法中,我按如下方式设置适配器,

adapter = new StatusAdapter(getActivity().getApplicationContext(), masterItems);
mListView.setAdapter(adapter);
 adapter.notifyDataSetChanged();

问题是多次调用getView。如何解决这个问题?有没有像我可以在添加新元素之前重置我的UI?因为多次调用getView,所以用多次相同的值更新ui

2 个答案:

答案 0 :(得分:1)

查看代码:

@Override 
public int getCount() { 
    return listForView.size();
} 

getView()迭代基于您的列表大小。 如果只需要迭代一次,请设置一个静态整数。

@Override 
public int getCount() { 
    return 1; // Just one getView() iteration
} 

但这不是适配器的最佳实践

getView()方法不是父迭代。 这是您列表中的项目,您可以使用它为列表中的每个项目创建视图。

答案 1 :(得分:1)

为每个列表项调用get视图,您无需解决此问题,优化列表视图您可以尝试ViewHolder模式(example)