Дублирование элемента ListView при прокрутке вниз
Я получаю дубликаты элементов при прокрутке вниз или переключаюсь в альбомный режим, я читал некоторые посты на эту тему, прежде чем публиковать этот новый, но большинство из них объясняют ловушку "еще" if), который у меня уже есть в моем коде, но он все равно становится дублирующим.
Я собираюсь привести простой пример того, что является моей проблемой, у меня есть ListView на моем макете "Платежи", как следует из названия, мой ListView будет отображать каждый платеж, который я зарегистрировал в моей базе данных.
В основном я использую customerAdapter, который расширяет BaseAdapter, этот адаптер работает на 2 listView, полностью отличающихся друг от друга, один для оплаты, а другой для продажи, мой конструктор customAdapter имеет 3 параметра
(Activity activity, ArrayList<Item_Venta_Gasto>, int tipo)
Item_Venta_Gasto - это класс, в котором я прежде, чем адаптировать данные к своему списку, я устанавливаю эти данные в этот класс, и затем я добавляю каждый объект в свой ArrayList для отправки в мой пользовательский адаптер.
В настоящее время у меня есть 8 записей в моем ListView, 6 из которых отображаются отлично, но когда я прокручиваю вниз представление списка, остальные 2 оставшиеся отображаются как дубликаты первых 2 элементов, я не уверен, что вы понимаете что я объясняю, я выложу скриншот, чтобы было понятно. То же самое происходит, когда я переключаю свой телефон в ландшафтный режим
Код CustomAdapter:
public class VentaGastoListAdapter extends BaseAdapter{
private Activity activity;
ArrayList<Item_Venta_Gasto> arrayitms;
int tipo;
public VentaGastoListAdapter(Activity activity, ArrayList<Item_Venta_Gasto> arrayitms, int tipo) {
this.activity = activity;
this.arrayitms = arrayitms;
this.tipo = tipo;
}
public View getView(int position, View convertView, ViewGroup parent) {
Fila1 view = null;
LayoutInflater inflator = activity.getLayoutInflater();
Item_Venta_Gasto itm;
if(convertView==null)
{
switch (tipo){
case 0:
view = new Fila1();
//Creo objeto item y lo obtengo del array
itm = arrayitms.get(position);
convertView = inflator.inflate(R.layout.gasto_item, null);
//Fecha
view.fecha = (TextView) convertView.findViewById(R.id.rowDate);
//Seteo en el campo titulo el nombre correspondiente obtenido del objeto
view.fecha.setText(itm.getFecha());
//descipcion
view.descripcion = (TextView) convertView.findViewById(R.id.rowDescription);
//Seteo la descripcion
view.descripcion.setText(itm.getConcepto()+" - "+itm.getDescripcion());
//saldo
view.saldo = (TextView)convertView.findViewById(R.id.rowPrice);
//seteo el saldo
view.saldo.setText(itm.getSaldo()+"BsF");
convertView.setTag(view);
break;
case 1:
view = new Fila1();
//Creo objeto item y lo obtengo del array
itm = arrayitms.get(position);
convertView = inflator.inflate(R.layout.gasto_item, null);
//Fecha
view.fecha = (TextView) convertView.findViewById(R.id.rowDate);
//Seteo en el campo titulo el nombre correspondiente obtenido del objeto
view.fecha.setText(itm.getFecha());
//descipcion
view.descripcion = (TextView) convertView.findViewById(R.id.rowDescription);
//Seteo la descripcion
view.descripcion.setText(itm.getCliente()+" "+itm.getCantidad()+" "+itm.getProducto());
//saldo
view.saldo = (TextView)convertView.findViewById(R.id.rowPrice);
//seteo el saldo
view.saldo.setText(itm.getSaldo()+"BsF");
convertView.setTag(view);
break;
}
}
else
{
view = (Fila1) convertView.getTag();
}
return convertView;
}
Item_Venta_Gasto Структура:
public class Item_Venta_Gasto {
int id;
String fecha;
String concepto;
String descripcion;
String saldo;
String producto;
String cliente;
String cantidad;
Context context;
public Item_Venta_Gasto(int id, String fecha, String producto, String cliente, String cantidad, String saldo, Context context) {
this.context = context;
this.id = id;
this.fecha = fecha;
this.producto = producto;
this.cliente = cliente;
this.cantidad = cantidad;
this.saldo = saldo;
this.concepto = null;
this.descripcion = null;
}
public Item_Venta_Gasto(int id, String fecha, String concepto, String descripcion, String saldo) {
this.id = id;
this.fecha = fecha;
this.concepto = concepto;
this.descripcion = descripcion;
this.saldo = saldo;
this.producto = null;
this.cliente = null;
this.cantidad = null;
}
Getter and Setter methods....
Фрагмент, где установлен ListView:
public class GastoFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ListView lista = (ListView) view.findViewById(R.id.gastoListView);
Cursor cursor = db.cargarCursorOrderBy("gasto",new String[]{"*"},"fecha");
ArrayList<Item_Venta_Gasto> listaGasto = new ArrayList<Item_Venta_Gasto>();
if(cursor.moveToFirst()){
for(int i = 0; i < cursor.getCount(); i++){
listaGasto.add(new Item_Venta_Gasto(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)));
cursor.moveToNext();
}
}
VentaGastoListAdapter adapter = new VentaGastoListAdapter(getActivity(),listaGasto,0);
lista.setAdapter(adapter);
return view;
}
Вот пара скриншотов, чтобы показать вам проблему.
Это первый вид ListView
Это когда я прокручиваю вниз ListView
и это база данных таблиц, где данные собираются
1 ответ
Попробуйте этот код в вашем адаптере getView
public View getView(int position, View convertView, ViewGroup parent) {
Fila1 view = null;
Item_Venta_Gasto itm;
if(convertView==null) {
view = new Fila1();
LayoutInflater inflator = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.gasto_item, null);
view.fecha = (TextView) convertView.findViewById(R.id.rowDate);
view.descripcion = (TextView) convertView.findViewById(R.id.rowDescription);
view.saldo = (TextView)convertView.findViewById(R.id.rowPrice);
convertView.setTag(view);
}else{
view = (Fila1) convertView.getTag();
}
itm = arrayitms.get(position);
view.fecha.setText(itm.getFecha());
view.saldo.setText(itm.getSaldo()+"BsF");
switch (tipo){
case 0:
view.descripcion.setText(itm.getConcepto()+" - "+itm.getDescripcion());
break;
case 1:
view.descripcion.setText(itm.getCliente()+" "+itm.getCantidad()+" "+itm.getProducto());
break;
}
return convertView;
}
Надеюсь это поможет!