I am currently adding TextViews inside a LinearLayout inside a ListView element using a for loop, because the amount of TextViews I have to add in there is variable. I am adding the items to the ListViews like you normally do. The problem is, when I scroll the items start to get more and more and when I scroll back up I end up with hundreds of items. I think it is because the ListView is reloading and cycling through the for loop once again and so adding every TextView multiple times. Can I stop that?
My code:
public class ListViewAdapter extends ArrayAdapter<RowItem> {
private final Context context;
public ListViewAdapter(Context context, List<RowItem> items) {
super(context, R.layout.list, items);
this.context = context;
}
private class ViewHolder {
TextView title;
LinearLayout linearLayout;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.list_line);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.list_linear);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(rowItem.getTitle());
String data = rowItem.getData();
String[] split0 = data.split("=");
Log.e("DATA", data);
Log.e("LINE", rowItem.getTitle());
for (int j = 0; j < split0.length; j++) {
String[] split1 = split0[j].split(":");
LinearLayout parentLayout = new LinearLayout(MainActivity.context);
parentLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parentLayout.setOrientation(LinearLayout.HORIZONTAL);
for (int k = 0; k < split1.length; k++) {
TextView textView = new TextView(MainActivity.context);
textView.setText(split1[k]);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
textView.setTextSize(18);
parentLayout.addView(textView);
}
holder.linearLayout.addView(parentLayout);
}
return convertView;
}
}
My data sceme looks like this for one entry:
text1:text2=text3:text4
How it will look on the list:
text1 text2
text3 text4