Search code examples
androidandroid-listviewandroid-arrayadapterlistadapter

Optimized way to use getView method in Adapter


I understand, calling every time view.findViewById(R.id.title); is much costly operation. How can i optimize this by storing these int values. What is the optimized way to use in List Adapter?

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        final DataObject dataObject = getItem(position);
        if (view == null) {
        // No view created yet
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        view = layoutInflater.inflate(layoutResourceId, parent, false);
        }
        if (view != null) {
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView price = (TextView) view.findViewById(R.id.price);
        ImageView img = (ImageView) view.findViewById(R.id.profile_pic);
        RatingBar overallRating = (RatingBar)                                                 view.findViewById(R.id.overall_rating);

Solution

  • you should use viewholder like this:

    ViewHolder holder;
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.chocolate_list_item,
                    parent, false);
            holder.txtvwChocolateName = (TextView) convertView
                    .findViewById(R.id.xtxtvwChocolateName);
            holder.imgvwChocolateIcon=(ImageView)convertView.findViewById(R.id.ximgvwChocolateIcon);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
    
        holder.txtvwChocolateName.setText(alChocolate.get(position)
                .getStrChocolateName());
        holder.imgvwChocolateIcon.setImageResource(images[position]);
        return convertView;
    }
    
    class ViewHolder {
        TextView txtvwChocolateName;
        ImageView imgvwChocolateIcon;
    }