0

I have an Adapter with ViewHolder. Let's say I want to set data only once to the ViewHoler inside the getView() method, what's actually happened is, its set the data every time I'm scrolling the view.

How can I check if the ViewHolder was already init or not?

public View getView(final int position, View convertView, ViewGroup parent) {
 final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
 convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
Deal deal = dealsArr.get(position);
holder.textView.setText(deal.getPrice);

// Here is my issue. how can I do it only once?
changePrice(deal, true);
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Igor F.
  • 55
  • 4
  • You don't want to do that. The `AdapterView` (`ListView`, `GridView`, what have you) is reusing those `View`s for different positions. If you don't update the `View`s accordingly, your items aren't going to display correctly. – Mike M. Jan 21 '18 at 13:59

1 Answers1

2

I asssume you already have the basic understanding of Android Adapters & working of getCount() & getView() if not see this


Either adapter returns a null View or an Inflated View; findViewbyId(R.id.xmlID) is always executed; ViewHolder is used to avoid frequent call and ensure the smooth scrolling of your listview.

Excellent Explanation here


First spend sometime of understand Listview's recycling mechanism! The link I had shared also has a link to that.!


public View getView(final int position, View convertView, ViewGroup parent) {
    //rest of the code goes here

}

focus on the parameters of this method, the convertViewwhich is for recycling will be null initially because there is no recycling done yet so this part of the code will be executed;

if (convertView == null) {  //convertView is null when recycling isn't done
            holder = new ViewHolder();
 convertView.setTag(holder);
        }

so we initialize the view-holder & refer all our Views(Buttons, TextViews etc) using findview by id.

the next time getView() is called; it executes this part of the code;

else {
            holder = (ViewHolder) convertView.getTag();
        }

I'd strongly recommend to first understand working of Android Adapters & List View Recyling Mechanism without using ViewHolders in your code. first you understand how & when the methods are invoked then use ViewHolder for more optimization

Salman Anjum
  • 333
  • 3
  • 7