0

это мой первый пост, и у меня есть сомнения относительно управления элементами списка, я видел сообщение о recycleView, но я не знаю, Не понимаю, как это реализовать в моей проблеме.Android Listview item, когда я реализую setCheck (true) в любом флажке, какой-то элемент изменен случайно

Ну, у меня есть listView, который показывает некоторые элементы, такие как торговый автомобиль, где пользователь нажимает кнопку autorizarDetalleSolicitud, которая открывает alertDialog, где пользователь выбирает желаемое количество соответствующего элемента, поэтому, если сумма больше чем ноль, флажок изменяется в состояние TRUE, но когда я проверяю эту функцию, я вижу, что другие checkBoxes активируются (или изменяются в состояние TRUE) случайным образом; т. е. когда я ввожу сумму в первый элемент, состояние предпоследнего checkBox изменяется на значение ИСТИНА. Спасибо за внимание.

//Button of each listview item 
public void autorizarDetalleSolicitud(View v) { 


    LinearLayout layoutboton = (LinearLayout) v.getParent(); 
    checkBoxelemento = (CheckBox) layoutboton.getChildAt(0); 

    RelativeLayout relativeLayout = (RelativeLayout) layoutboton.getParent(); 
    TableLayout tableLayout = (TableLayout) relativeLayout.getChildAt(1); 
    TextView tipoelementotextview = (TextView) tableLayout.findViewById(R.id.tipoelem); 
    TextView unidadelem = (TextView) tableLayout.findViewById(R.id.unidadelem); 
    TextView idelem = (TextView) tableLayout.findViewById(R.id.idelem); 
    TextView cantpedida = (TextView) tableLayout.findViewById(R.id.cantidadelem); 
    cantautorizadatextview = (TextView) tableLayout.findViewById(R.id.cantautorizado); 
    final String tipoelemento = tipoelementotextview.getText().toString(); 

    cantidadpedida = Double.parseDouble(cantpedida.getText().toString()); 
    cantidadautorizada = Double.parseDouble(cantautorizadatextview.getText().toString()); 
    idelemento = idelem.getText().toString(); 

    // configura el alert dialog 
    builder = new AlertDialog.Builder(this); 
    builder.setMessage(unidadelem.getText() + " a autorizar:"); 
    builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
     } 
    }); 

    if (tipoelemento.equals("Material")) { 
     numberPickerCantidad = new NumberPicker(getApplicationContext()); 
     numberPickerCantidad.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary)); 
     numberPickerCantidad.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); 


     String[] nums = new String[100]; 
     for (int i = 0; i < nums.length; i++) { 
      nums[i] = Integer.toString(i); 
     } 
     numberPickerCantidad.setMinValue(0); 
     numberPickerCantidad.setMaxValue(nums.length - 1); 
     numberPickerCantidad.setWrapSelectorWheel(false); 
     numberPickerCantidad.setDisplayedValues(nums); 
     if(cantidadautorizada==0){ 
      numberPickerCantidad.setValue(cantidadpedida.intValue()); 
     }else{ 
      numberPickerCantidad.setValue(cantidadautorizada.intValue()); 
     } 

     builder.setPositiveButton(R.string.agregar, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       int cantidadautorizada = numberPickerCantidad.getValue(); 
       autorizarCantidad((double)cantidadautorizada,tipoelemento); 
      } 
     }); 
     builder.setView(numberPickerCantidad); 

    } else { 
     cantreactivosoli = new EditText(getApplicationContext()); 
     cantreactivosoli.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
     cantreactivosoli.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)}); 
     cantreactivosoli.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary)); 

     if(cantidadautorizada==0){ 
      cantreactivosoli.setText(cantidadpedida + ""); 
     }else{ 
      cantreactivosoli.setText(cantidadautorizada + ""); 
     } 

     cantreactivosoli.setText(cantidadpedida + ""); 
     builder.setView(cantreactivosoli); 
     builder.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       String cantidadedittext = cantreactivosoli.getText().toString(); 
       if (!cantidadedittext.equals("")) { 
        Double cantidadingresada = Double.parseDouble(cantidadedittext); 
        autorizarCantidad(cantidadingresada,tipoelemento); 
       } else { 
        Toast toast = Toast.makeText(getApplicationContext(), R.string.error_sincantidad, Toast.LENGTH_SHORT); 
        toast.show(); 
       } 
      } 
     }); 
     builder.setView(cantreactivosoli); 
    } 

    builder.show(); 
} 

// Method that saves the input value in an arraylist and implements a setCheck(true) of that itemstrong text 
public void autorizarCantidad(Double cantidadingresada, String tipoelemento){ 

    if (cantidadingresada <= cantidadpedida) { 
     int flag = 0; 
     for (int indice = 0; indice < elementosrevisados.size(); indice++) { 
      if (elementosrevisados.get(indice).getId().equals(idelemento)) { 
       elementosrevisados.get(indice).setCantidadAutorizada(cantidadingresada+""); 
       if (tipoelemento.equals("Material")) { 
        cantautorizadatextview.setText(cantidadingresada.intValue()+""); 
       }else{ 
        cantautorizadatextview.setText(cantidadingresada+""); 
       } 
       cantidadpedida = cantidadingresada; 
       flag=1; 
       break; 
      } 
     } 

     if(flag==0) { 
      Elemento elem = new Elemento(idelemento, cantidadpedida + "", cantidadingresada + ""); 
      elementosrevisados.add(elem); 
      checkBoxelemento.setChecked(true); 
      if (tipoelemento.equals("Material")) { 
       cantautorizadatextview.setText(cantidadingresada.intValue()+""); 
      }else{ 
       cantautorizadatextview.setText(cantidadingresada+""); 
      } 
     } 

     for(int i=0;i<elementosrevisados.size();i++){ 
      Log.e("Elemento revisado: ",elementosrevisados.get(i).toString()); 
     } 
    } else { 
     Toast toast = Toast.makeText(getApplicationContext(), R.string.error_cantidadautorizada, Toast.LENGTH_SHORT); 
     toast.show(); 
    } 

} 
+1

Необходимо сохранить позицию щелкнутого виджета. Для получения дополнительной информации см. Http://stackoverflow.com/a/38887338/2404262 –

+0

@AnshulTyagi спасибо, я думал о чем-то подобном. –

+0

дайте мне знать, если это работает –

ответ

1

РЕШЕНИЕ!

Чтобы решить мою проблему, я основывался на этом answer, записывая массив с позициями флажков, проверяя, были ли они отмечены, я имею в виду, что это булевой массив, и каждый флажок имеет статус ИСТИНА или ЛОЖЬ. Благодаря @AnshulTyagi

public class ElementoAdapter extends BaseAdapter { 

    private ArrayList<Boolean> status = new ArrayList<Boolean>(); 
    private static LayoutInflater inflater = null; 
    private ArrayList<HashMap<String, String>> data; 
    Activity activity; 

    CompoundButton.OnCheckedChangeListener miCheckedListener = new CompoundButton.OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(CompoundButton checkBoxView,boolean isChecked){ 

      int posicioncheck = (Integer)checkBoxView.getTag(); 

      if (checkBoxView.isChecked()) { 

       status.set(posicioncheck,true); 

      } else { 

       status.set(posicioncheck,false); 
      } 
     } 
    }; 

    public ElementoAdapter(Activity activity, ArrayList<HashMap<String, String>> data){ 
     this.activity = activity; 
     this.data = data; 
     inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     for (int i = 0; i < data.size(); i++) { 
      status.add(false); 
     } 
    } 


    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return position; 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView (int position, View convertView, ViewGroup parent) { 
     View vista = convertView; 
     ViewHolder holder; 
     if (vista == null) { 
      vista = inflater.inflate(R.layout.listitem_elemento,null); 
      holder = new ViewHolder(); 
      holder.labelIdElemento = (TextView) vista.findViewById(R.id.labelIdElemento); 
      holder.idElemento = (TextView) vista.findViewById(R.id.idelem); 
      holder.labelTipo = (TextView) vista.findViewById(R.id.labelTipoElemento); 
      holder.tipoElemento = (TextView) vista.findViewById(R.id.tipoelem); 
      holder.labelCodigoElemento = (TextView) vista.findViewById(R.id.labelCodigo); 
      holder.codigoElemento = (TextView) vista.findViewById(R.id.codigoelem); 
      holder.labelDescripcionElemento= (TextView) vista.findViewById(R.id.labelDescripcion); 
      holder.descripcionElemento = (TextView) vista.findViewById(R.id.descripcionelem); 
      holder.labelMarcaElemento = (TextView) vista.findViewById(R.id.labelMarca); 
      holder.marcaElemento = (TextView) vista.findViewById(R.id.marcaelem); 
      holder.labelUnidadMedida = (TextView) vista.findViewById(R.id.labelUnidadMedida); 
      holder.unidadMedida = (TextView) vista.findViewById(R.id.unidadelem); 
      holder.checkBoxElemento = (CheckBox) vista.findViewById(R.id.checkBox); 
      holder.botonElemento = (Button) vista.findViewById(R.id.botonsolic); 

      vista.setTag(holder); 

     } else { 
      holder = (ViewHolder) convertView.getTag(); 
      // remove the listener so that it does not get attached to other chechboxes. 
      holder.checkBoxElemento.setOnCheckedChangeListener(null); 
      holder.checkBoxElemento.setChecked(status.get(position)); 
      Log.e("check "+position,status.get(position)+""); 

     } 

     holder.idElemento.setText(data.get(position).get("idelemento")); 
     holder.tipoElemento.setText(data.get(position).get("tipoelemento")); 
     holder.codigoElemento.setText(data.get(position).get("codigoelemento")); 
     holder.descripcionElemento.setText(data.get(position).get("descripcionelemento")); 
     holder.marcaElemento.setText(data.get(position).get("marcaelemento")); 
     holder.unidadMedida.setText(data.get(position).get("unidadmedida")); 
     Log.e("idelemento creado ",data.get(position).get("idelemento")); 
     holder.checkBoxElemento.setTag(position); 



//add a custom listener 
     holder.checkBoxElemento.setOnCheckedChangeListener(miCheckedListener); 

     return vista; 
    } 

    static class ViewHolder { 
     TextView labelIdElemento; 
     TextView idElemento; 
     TextView labelTipo; 
     TextView tipoElemento; 
     TextView labelCodigoElemento; 
     TextView codigoElemento; 
     TextView labelDescripcionElemento; 
     TextView descripcionElemento; 
     TextView labelMarcaElemento; 
     TextView marcaElemento; 
     TextView labelUnidadMedida; 
     TextView unidadMedida; 
     CheckBox checkBoxElemento; 
     Button botonElemento; 
    } 

}