0

I created my own adapter that extend BaseAdapter and I use it for GridView. I want to get the number of element and put it into TextView. I did it in my adapter:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;

        if(convertView == null){
            gridView = new View(context);

            gridView = inflater.inflate(R.layout.grid_element, null);

            ImageView logo = (ImageView) gridView.findViewById(R.id.grid_logo);


            TextView tv = (TextView) gridView.findViewById(R.id.grid_textView1);
            tv.setText(level+position);
        }
        else
            gridView = convertView;

        return gridView;
    }

It seems to be good until I get elements that are not in the screen in launch: enter image description here

The position is like reseted. How can I do it properly?

Mateusz Kaflowski
  • 2,221
  • 1
  • 29
  • 35

2 Answers2

2

You were not setting the TextView properly when convertView was not null. Try this:

if (convertView == null) {
    gridView = inflater.inflate(R.layout.grid_element, null);
} else {
    gridView = convertView;
}

ImageView logo = (ImageView) gridView.findViewById(R.id.grid_logo);

TextView tv = (TextView) gridView.findViewById(R.id.grid_textView1);
tv.setText(level + position);
minipif
  • 4,756
  • 3
  • 30
  • 39
1

May help new Visitors.

You have to know two main things :

  1. You need to check if convertView is null, in order to know if that row in your list is not created yet (convertView = null) or is being recycled by the adapter (convertView != null). This is called the Recycling process.

  2. Another important thing to know is the View Holder Pattern. Calling findViewById() on each row of getView() method is to heavy for list populating and slows down scrolling performance. To avoid that, create a static class with some views as class fields. Than use findViewById() if the view is being created (convertView == null), and get it back from getTag() method when it's being recycled

`

static class ViewHolder {
    TextView text;
    ImageView icon;
}

ViewHolder holder;
if(convertView == null) {
    convertView = inflater.inflate(resource, root); 
    holder = new ViewHolder();
    holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);
    holder.text = (TextView) convertView.findViewById(R.id.listitem_text);
    holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp);
    holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);
    convertView.setTag(holder);
}

holder = (ViewHolder) convertView.getTag();

// Set here your view's content : 
holder.text.setText("Sample"); 
// ...
Community
  • 1
  • 1
S.Thiongane
  • 6,883
  • 3
  • 37
  • 52