Флажок внутри представления списка автоматически проверяет и снимает флажок при прокрутке

Я знаю, что этот вопрос задавался снова и снова, но до сих пор я не нашел/не понял ничего из того, что нашел. Флажок снимается всякий раз, когда список прокручивается вниз, или некоторые флажки устанавливаются всякий раз, когда список прокручивается вверх.

Вот мой код:

@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
    //View v = View.inflate(mContext, R.layout.sales_invoice_custom,null);
    final ViewHolder holder;

    if (view == null) {
        view = View.inflate(mContext, R.layout.sales_invoice_custom, null);
        holder = new ViewHolder();

        holder.SelectInvoiceCB = (CheckBox) view.findViewById(R.id.selectInvoiceCB);
        holder.SalesInvoiceNo = (TextView) view.findViewById(R.id.SINo);
        holder.InvoiceDate = (TextView) view.findViewById(R.id.SIDate);
        holder.InvoiceAmount = (TextView) view.findViewById(R.id.SIAmount);
        holder.AmountDue = (TextView) view.findViewById(R.id.SIAmountDue);
        holder.DueDate = (TextView) view.findViewById(R.id.SIdueDate);
        holder.PayFull = (CheckBox) view.findViewById(R.id.SIFull);
        holder.PayPartial = (CheckBox) view.findViewById(R.id.SIPartial);
        holder.TotalAmount = (EditText) view.findViewById(R.id.SITotalAmount);
        holder.CreditMemoID = (TextView) view.findViewById(R.id.creditMemoID);
        holder.CreditMemoDate = (TextView) view.findViewById(R.id.creditMemoDate);
        holder.CreditMemoReason = (TextView) view.findViewById(R.id.creditMemoReason);
        holder.LL2 = (LinearLayout) view.findViewById(R.id.ll2);
        holder.LL3 = (LinearLayout) view.findViewById(R.id.ll3);

        view.setTag(holder);

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

    InvoicePopulate(holder,position);

    return view;
}


public void InvoicePopulate(final ViewHolder holder, final int position) {
    dbHelper = new DBHelper(mContext);

    Calendar c = Calendar.getInstance();
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    final String formattedDate = df1.format(c.getTime());


            //holder.SelectInvoiceCB.setChecked(false);
            holder.SalesInvoiceNo.setText(invoiceLists.get(position).getSales_Invoice_ID());
            holder.InvoiceDate.setText(invoiceLists.get(position).getInvoice_Date());
            holder.DueDate.setText(invoiceLists.get(position).getDue_Date());

            float invAmount = 0;
            invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
            holder.InvoiceAmount.setText(String.format("%,.2f",invAmount));
            holder.AmountDue.setText(String.format("%,.2f",invAmount));


            try {
                if (invoiceLists.get(position).getAmount_Paid().toString().equals("") ||
                        invoiceLists.get(position).getAmount_Paid().toString().equals("0")) {
                    invAmount = 0;
                    invAmountDue = 0;
                    invAmountPaid = 0;

                    invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                    invAmountDue = invAmount - invAmountPaid;
                    Log.e("Without AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
                } else {
                    invAmount = 0;
                    invAmountDue = 0;
                    invAmountPaid = Math.round(Float.parseFloat(invoiceLists.get(position).getAmount_Paid())*100.00)/(float)100.00;
                    invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                    invAmountDue = invAmount - invAmountPaid;
                    Log.e("With AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
                }

                final float finalInvAmount = invAmountDue;
                holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (holder.PayFull.isChecked()) {
                            holder.PayPartial.setChecked(false);
                            if (holder.SelectInvoiceCB.isChecked()) {
                                invoiceStatusValue = "PAID_FULL";
                                holder.TotalAmount.setText(String.valueOf(Math.round(finalInvAmount*100.00)/100.00));
                                //holder.TotalAmount.setText(holder.InvoiceAmount.getText().toString());
                            }
                        }
                    }
                });

                holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (holder.PayPartial.isChecked()) {
                            holder.PayFull.setChecked(false);
                            if (holder.SelectInvoiceCB.isChecked()) {
                                invoiceStatusValue = "PAID_PARTIAL";
                                holder.TotalAmount.setText("0.00");
                            }
                        }
                    }
                });

                holder.AmountDue.setText(String.format("%,.2f",invAmountDue));
            } catch (Exception e) {
                e.getMessage();
            }

            if (TotalPaymentAmount >= Float.parseFloat(String.valueOf(invAmountDue))) {
                holder.SelectInvoiceCB.setChecked(true);
                holder.PayFull.setChecked(true);
                holder.PayFull.setClickable(true);
                holder.PayPartial.setClickable(true);

                holder.TotalAmount.setText(String.valueOf(Math.round(invAmountDue*100.00)/100.00));
            }

        }


    } catch (Exception e){
        e.getMessage();
        System.out.println("Error - " + e);
    } finally {
        dbHelper.close();
    }
}

person Eugene Santos    schedule 08.11.2017    source источник
comment
попробуйте по этой ссылке, может быть это будет полезно для вас. stackoverflow.com/ вопросов/10895763/ stackoverflow.com/questions/9309250/   -  person Jinal Awaiya    schedule 08.11.2017


Ответы (3)


Вы должны сохранить флажок установлен или нет в вашем классе модели представления.Ex. логическое значение проверено; чем в getView() установить флажок из viewmodel ischecked.

person Nirav Shah    schedule 08.11.2017

Вы должны управлять проверенным состоянием в классе модели. В вашем случае вам нужно управлять тремя логическими значениями для установленного флажка PayFull, PayPartial и SelectInvoiceCB. Когда вы сделали setChecked в это время, обновите проверенное поведение класса модели, например:

    class YourModel{
              public boolean isPayFull, isPayPartial, isSelectInvoice;
        }

        //This will update UI from model check behaviour
        holder.PayFull.setChecked(invoiceLists.get(position).isPayFull);
        holder.PayPartial.setChecked(invoiceLists.get(position).isPayPartial);
        holder.SelectInvoiceCB.setChecked(invoiceLists.get(position).isSelectInvoice);    
        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (holder.PayFull.isChecked()) {
                                    holder.PayPartial.setChecked(false);
                                    if (holder.SelectInvoiceCB.isChecked()) {
                                        invoiceStatusValue = "PAID_FULL";

                                    }
                                }
    //This is to manage the state of checkbox in model
    invoiceLists.get(position).isPayFull = holder.PayFull.isChecked();
    invoiceLists.get(position).isPayPartial= holder.PayPartial.isChecked();
    invoiceLists.get(position).isSelectInvoice= holder.SelectInvoiceCB.isChecked();
                            }
                        });

                        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (holder.PayPartial.isChecked()) {
                                    holder.PayFull.setChecked(false);
                                    if (holder.SelectInvoiceCB.isChecked()) {
                                        invoiceStatusValue = "PAID_PARTIAL";
                                        holder.TotalAmount.setText("0.00");
                                    }
                                }
    //This is to manage the state of checkbox in model
    invoiceLists.get(position).isPayFull = holder.PayFull.isChecked();
    invoiceLists.get(position).isPayPartial= holder.PayPartial.isChecked();
    invoiceLists.get(position).isSelectInvoice= holder.SelectInvoiceCB.isChecked();
                            }
                        });

Как правило, я предпочитаю делать события щелчка на флажке, а не проверять прослушиватели изменений в элементе списка, проверенное изменение будет получать вызов при прокрутке и обновлять пользовательский интерфейс при каждой прокрутке, поэтому лучше применять событие щелчка на флажке и управлять проверенным состоянием из класса модели, как я упомянул тебя.

person Ready Android    schedule 08.11.2017
comment
Привет, сэр, это хорошо! Спасибо. Но когда я снимаю флажок и прокручиваю список, он возвращается к проверке. - person Eugene Santos; 08.11.2017

В ответ на ваш вопрос причина, по которой он проверяет и снимает отметку, заключается в этом фрагменте вашего кода во всех CheckChangedListeners

if (holder.PayFull.isChecked()) {
      holder.PayPartial.setChecked(false);

Вы снимаете флажок, как только он установлен.

В отдельной заметке вам нужно обрабатывать проверенные состояния во время повторного использования представления. В противном случае флажки не будут поддерживать правильное состояние. при прокрутке.

Один из вариантов — сохранить состояния в ArrayList вместе с вашими данными. Сохраните 3 логические переменные state1, state2, state3 для флажков.

В методе InvoicePopulate(...) -

holder.PayFull.setChecked(invoiceLists.get(position).getState1())  

В проверке измененного слушателя добавьте следующую строку

invoicelists.get(position).setState1(isChecked)

person Deepak    schedule 08.11.2017