public class CustomerProductAdapter extends BaseAdapter {
Context ccon;
ImageView cprdctimg;
LayoutInflater cprdctinflater;
View cprdctview;
TextView cprdctname,cprdctdesc,cprdctprice,cprdctquant,cpquantity;
ArrayList<Product> cproduct;
Product currentproduct;
Button cpincq,cpdecq;
@Override
public int getCount() {
return cproduct.size();
}
@Override
public Object getItem(int i) {
return cproduct.get(i).getPname();
}
public CustomerProductAdapter(Context con,ArrayList<Product> product) {
this.cproduct=product;
this.ccon = con;
cprdctinflater=LayoutInflater.from(con);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, final ViewGroup viewGroup) {
cprdctview=cprdctinflater.inflate(R.layout.cplist,null);
cpincq=cprdctview.findViewById(R.id.cpincq);
cpquantity=cprdctview.findViewById(R.id.cpquantity);
cpdecq=cprdctview.findViewById(R.id.cpdecq);
cprdctname=cprdctview.findViewById(R.id.cpname);
cprdctdesc=cprdctview.findViewById(R.id.cpdesc);
cprdctimg=cprdctview.findViewById(R.id.cppic);
cprdctprice=cprdctview.findViewById(R.id.cpprice);
cprdctquant=cprdctview.findViewById(R.id.cpquant);
currentproduct=cproduct.get(i);
cprdctimg.setImageResource(cproduct.get(i).getPimage());
cprdctname.append(cproduct.get(i).getPname().toString());
cprdctdesc.append(cproduct.get(i).getPdesc().toString());
cprdctprice.append(cproduct.get(i).getPprice().toString());
cprdctquant.append(cproduct.get(i).getPquant());
cpincq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentproduct.inccustomerquantity();
if (currentproduct.getcustomerquantity()>Integer.parseInt(currentproduct.getPquant()))
{
Toast.makeText(viewGroup.getContext(), "You cannot order more than stock", Toast.LENGTH_SHORT).show();
currentproduct.deccustomerquantity();
}
else {
cpquantity.setText("" + currentproduct.getcustomerquantity());
}
}
});
cpdecq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (currentproduct.deccustomerquantity()) {
cpquantity.setText("" + currentproduct.getcustomerquantity());
}
}
});
return cprdctview;
}
}
Здесь, если я увеличиваю количество одного продукта в списке, соответствующий TextView не изменяется, а изменяется какой-то другой TextView в другом элементе списка. Как вы можете видеть на изображении, количество винограда меняется, когда я нажимаю на символ «+» в банане. Пожалуйста, помогите мне исправить эту ошибку, чтобы изменения были внесены только в соответствующее текстовое представление.




Когда вы нажимаете кнопку, вам нужно изменить модель в списке, а не пользовательский интерфейс. После этого обновите нужное положение адаптера. Предлагаю вам взглянуть на шаблон ViewHolder.
GetView () вызывается каждый раз при создании строки. Поэтому ваши глобальные переменные / переменные экземпляра (currentproduct, cprdctname, cprdctdesc ...) всегда относятся к последней созданной строке (при прокрутке вверх - к нижней; при прокрутке вниз - к верхней). Вы можете сохранить позицию строки элемента как Ярлык для кнопок и обновить соответствующий элемент в списке данных. Затем вызовите адаптер для перерисовки всех строк с помощью notifyDataSetChanged ().
Попробуй это:
@Override
public View getView(int i, View view, final ViewGroup viewGroup) {
cprdctview=cprdctinflater.inflate(R.layout.cplist,null);
cpincq=cprdctview.findViewById(R.id.cpincq);
cpquantity=cprdctview.findViewById(R.id.cpquantity);
cpdecq=cprdctview.findViewById(R.id.cpdecq);
cprdctname=cprdctview.findViewById(R.id.cpname);
cprdctdesc=cprdctview.findViewById(R.id.cpdesc);
cprdctimg=cprdctview.findViewById(R.id.cppic);
cprdctprice=cprdctview.findViewById(R.id.cpprice);
cprdctquant=cprdctview.findViewById(R.id.cpquant);
currentproduct=cproduct.get(i);
cprdctimg.setImageResource(cproduct.get(i).getPimage());
cprdctname.append(cproduct.get(i).getPname().toString());
cprdctdesc.append(cproduct.get(i).getPdesc().toString());
cprdctprice.append(cproduct.get(i).getPprice().toString());
cprdctquant.append(cproduct.get(i).getPquant());
cpincq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentproduct = cproduct.get((int)view.getTag()); // Get item for the clicked position
currentproduct.inccustomerquantity();
if (currentproduct.getcustomerquantity()>Integer.parseInt(currentproduct.getPquant()))
{
Toast.makeText(viewGroup.getContext(), "You cannot order more than stock", Toast.LENGTH_SHORT).show();
currentproduct.deccustomerquantity();
}
else {
//cpquantity.setText("" + currentproduct.getcustomerquantity());
notifyDataSetChanged();
}
}
});
cpdecq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentproduct = cproduct.get((int)view.getTag()); // Get item for the clicked position
if (currentproduct.deccustomerquantity()) {
//cpquantity.setText("" + currentproduct.getcustomerquantity());
notifyDataSetChanged();
}
}
});
// Save the current position as Tag to the buttons
cpincq.setTag(i);
cpdecq.setTag(i);
return cprdctview;
}
Надеюсь, это поможет!
Согласно официальной документации Android, не используйте позицию, поскольку она используется повторно. Рекомендуется использовать getAdapterPosition (). Итак, в вашем коде вместо listOfItems.get (i) используйте listOfItems (getAdapterPosition ())
Я обновил модель, как вы сказали. Смотрите строку
currentproduct.inccustomerquantity();. Что вы имеете в виду, обновляя желаемое положение адаптера. Я обновил модель. Но как обновить адаптер. Не могли бы вы привести пример.