4

레이아웃이있는 어댑터가있는 ListView를 가지고 있으므로 목록의 모든 항목에 스위치가 있습니다.ListView 용 어댑터 스위치

나는이 코드를 사용하려면 :

mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     // do something, the isChecked will be 
     // true if the switch is in the On position 
    } 
}); 

을하지만 그것을 사용하는 WHERE 나도 몰라 : 어댑터 클래스에서 또는 목록 포함하는 클래스에서, 나는 어떤 항목 오전 알고 얼마나을 할 수 스위치를 토글 할 때 수정되므로 속성을 수정할 수 있습니다.

편집 : 구현 된 메소드가있는 어댑터 클래스입니다. getView 메소드가 호출 될 때마다 실행되며 (스위치가 토글 될 때) 실행되지 않고 logcat에 로그가 표시되지만 토글 된 객체는 수정되지 않습니다. 아래로 스크롤하여 위로 스크롤 할 때, 스위치는 원래 상태로 돌아갑니다 :

package com.nahue.actions; 

import java.util.ArrayList; 

import android.app.Activity; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.CompoundButton; 
import android.widget.CompoundButton.OnCheckedChangeListener; 
import android.widget.Switch; 
import android.widget.TextView; 
import android.widget.Toast; 


/*@SuppressLint("ViewHolder") */public class AdapterActions extends ArrayAdapter<Action>{ 

    // our ViewHolder. 
    // caches our TextView 
    static class ViewHolderItem { 
     TextView codigo; 
     TextView accion; 
     TextView evento; 
     Switch UnSwitch; 
    } 

    Activity context; 
    ArrayList<Action> listaActions; 

    // Le pasamos al constructor el contexto y la lista de contactos 
    public AdapterActions(Activity context, ArrayList<Action> listaActions) { 
     super(context, R.layout.layout_adapter_actions, listaActions); 
     this.context = context; 
     this.listaActions = listaActions; 




    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 

     ViewHolderItem viewHolder; 

     // Rescatamos cada item del listview y lo inflamos con nuestro layout 
     //View item = convertView; 
     //item = context.getLayoutInflater().inflate(R.layout.layout_adapter_actions, null); 

     // well set up the ViewHolder 
     viewHolder = new ViewHolderItem(); 

     if(convertView==null){ 

      // inflate the layout 
      LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
      convertView = inflater.inflate(R.layout.layout_adapter_actions, parent, false); 

      // well set up the ViewHolder 
      viewHolder = new ViewHolderItem(); 
      viewHolder.codigo = (TextView) convertView.findViewById(R.id.codigo); 
      viewHolder.accion = (TextView) convertView.findViewById(R.id.accion); 
      viewHolder.evento = (TextView) convertView.findViewById(R.id.evento); 
      viewHolder.UnSwitch = (Switch) convertView.findViewById(R.id.activa); 

      // store the holder with the view. 
      convertView.setTag(viewHolder); 

     }else{ 
      // we've just avoided calling findViewById() on resource everytime 
      // just use the viewHolder 
      viewHolder = (ViewHolderItem) convertView.getTag(); 
     } 

     Action a = new Action(0, 1, 1, true); 
     Accion LaAccion = new Accion(0, "", ""); 
     Evento ElEvento = new Evento(0, "", ""); 

     //ACTIONS 
       ActionsSQLite base = new ActionsSQLite(context, "Actions", null,1); 
       SQLiteDatabase db1 = base.getReadableDatabase(); 
       db1 = context.openOrCreateDatabase("Actions",SQLiteDatabase.OPEN_READONLY, null); 

       String query = "SELECT * FROM Actions WHERE Id = " + String.valueOf(position + 1); 
       Cursor c1 = db1.rawQuery(query, null); 

       try{ 
        if(c1!=null){ 

         int i = c1.getColumnIndexOrThrow("Id"); 
         int j = c1.getColumnIndexOrThrow("IdAccion"); 
         int k = c1.getColumnIndexOrThrow("IdEvento"); 
         int l = c1.getColumnIndexOrThrow("Activa"); 
         boolean esActiva; 

         //Nos aseguramos de que existe al menos un registro 
         while(c1.moveToNext()){ 
          if (c1.getInt(l) == 0){ 
           esActiva = false; 
          } else 
          { 
           esActiva = true; 
          } 
          //Recorremos el cursor hasta que no haya más registros 
          a = new Action(c1.getInt(i), c1.getInt(j), c1.getInt(k), esActiva); 
         } 
        } 
        else 
         Toast.makeText(context.getApplicationContext(), 
            "No hay nada :(", Toast.LENGTH_LONG).show(); 
        } 
        catch (Exception e){ 
        Log.i("bdActions", "Error al abrir o crear la base de datos" + e); 
        } 

        if(db1!=null){ 
         db1.close(); 
       } 


     //EVENTOS 
     EventosSQLite base2 = new EventosSQLite(this.context, "Eventos", null, 1); 
     SQLiteDatabase db2 = base2.getReadableDatabase(); 
     db2 = context.openOrCreateDatabase("Eventos",SQLiteDatabase.OPEN_READONLY, null); 

     String query2 = "SELECT * FROM Eventos WHERE Id = " + a.getIdEvento(); 
     Cursor c2 = db2.rawQuery(query2, null); 
     try{ 
      if(c2!=null){ 

       int h = c2.getColumnIndexOrThrow("Id"); 
       int i = c2.getColumnIndexOrThrow("Nombre"); 
       int j = c2.getColumnIndexOrThrow("Descripcion"); 

       //Nos aseguramos de que existe al menos un registro 
       while(c2.moveToNext()){ 
        //Recorremos el cursor hasta que no haya más registros 
        ElEvento = new Evento(c2.getInt(h), c2.getString(i), c2.getString(j)); 
       } 
      } 
      else 
       Toast.makeText(context.getApplicationContext(), 
         "No hay nada :(", Toast.LENGTH_LONG).show(); 
     } 
     catch (Exception e){ 
      Log.i("bdEventos", "Error al abrir o crear la base de datos" + e); 
     } 

     if(db2!=null){ 
      db2.close(); 
     } 
     //ACCIONES 
     AccionesSQLite base3 = new AccionesSQLite(context, "acciones", null,1); 
     SQLiteDatabase db3 = base3.getReadableDatabase(); 
     db3 = context.openOrCreateDatabase("Acciones", SQLiteDatabase.OPEN_READONLY, null); 

     String query3 = "SELECT * FROM Acciones WHERE Id = " + String.valueOf(a.getIdAccion()); 
     Cursor c3 = db3.rawQuery(query3, null); 
     try{ 
      if(c3!=null){ 

       int h = c3.getColumnIndexOrThrow("Id"); 
       int i = c3.getColumnIndexOrThrow("Nombre"); 
       int j = c3.getColumnIndexOrThrow("Descripcion"); 

       //Nos aseguramos de que existe al menos un registro 
       while(c3.moveToNext()){ 
        //Recorremos el cursor hasta que no haya más registros 
        LaAccion = new Accion(c3.getInt(h), c3.getString(i), c3.getString(j)); 
       } 
      } 
      else 
       Toast.makeText(context.getApplicationContext(), 
         "No hay nada :(", Toast.LENGTH_LONG).show(); 
     } 
     catch (Exception e){ 
      Log.i("bdAcciones", "Error al abrir o crear la base de datos" + e); 
     } 

     if(db3!=null){ 
      db3.close(); 
     } 

     // object item based on the position 

     viewHolder.UnSwitch.setChecked(a.getActiva()); 
     // assign values if the object is not null 
     if(a != null) { 
      // get the TextView from the ViewHolder and then set the text (item name) and tag (item ID) values 
      viewHolder.codigo.setText(String.valueOf(a.getId())); 
      viewHolder.codigo.setTag(a.getId()); 
      viewHolder.accion.setText(LaAccion.getNombre()); 
      viewHolder.evento.setText(ElEvento.getNombre()); 
      viewHolder.UnSwitch.setChecked(a.getActiva()); 
     } 

     viewHolder.UnSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      //you can modify Action here. 
       Log.e("Listener del switch", "Entró"); 
      listaActions.get(position).setActiva(isChecked); 
      Log.e("Listener del switch", "Modificó la action en la lista del adapter"); 
      ActividadPrincipal.listaActions.get(position).setActiva(isChecked); 
      Log.e("Listener del switch", "Modificó la action en la lista de la ActividadPrincipal"); 
      int isActiva; 
      if(isChecked == true) 
      { 
       isActiva = 1; 
       Log.e("Listener del switch", "isActiva = 1"); 
      } else 
      { 
       isActiva = 0; 
       Log.e("Listener del switch", "isActiva = 0"); 
      } 
      String query = "UPDATE Actions SET Activa = " + String.valueOf(isActiva) + " WHERE Id = " + String.valueOf(position); 
      Log.e("Listener del switch", "query creado"); 
      ActionsSQLite helper1 = new ActionsSQLite(context, "Actions", null, 1); 
      Log.e("Listener del switch", "Creo el helper"); 
      SQLiteDatabase db = helper1.getWritableDatabase(); 
      Log.e("Listener del switch", "obtenida la base escribible"); 
      db.execSQL(query); 
      Log.e("Listener del switch", "Query ejecutado"); 
     }}); 



     return convertView; 
    } 
} 
+0

:

지금이 결과입니다. 어댑터 코드는 어디에 있습니까? – dannyroa

+0

수정 됨! 그 코드는 –

답변

6

해결.

OnCheckedChangeListener()의 문제점은 getView()을 실행할 때마다 메서드를 실행한다는 것입니다. 어떻게 해결 했습니까? 쉬운 : 나는 onClickListener()를 사용했고 코드는 스위치를 클릭 할 때만 실행됩니다. 어댑터 클래스에서

viewHolder.isChecked1 = viewHolder.UnSwitch.isChecked(); 
     map.put(position, viewHolder.isChecked1); 
     viewHolder.UnSwitch.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Log.e("OnClick", "Se clickeó"); 

       listaActions.get(position).setActiva(map.get(position)); 
       Log.e("Listener del switch", "Modificó la action en la lista de la ActividadPrincipal"); 
       int isActiva; 
       if(map.get(position) == true) 
       { 
        isActiva = 0; 
        Log.e("Listener del switch", "isActiva = 1"); 
        map.put(position, false); 
       } else 
       { 
        isActiva = 1; 
        Log.e("Listener del switch", "isActiva = 0"); 
        map.put(position, true); 
       } 
       String query = "UPDATE Actions SET Activa = " + String.valueOf(isActiva) + " WHERE Id = " + String.valueOf(position+1); 
       Log.e("Consulta:", query); 
       Log.e("Listener del switch", "query creado"); 
       Log.e("La position debería ser", String.valueOf(position+1)); 
       Log.e("Y el valor del map.get(position) es", String.valueOf(map.get(position))); 
       ActionsSQLite helper1 = new ActionsSQLite(context, "Actions", null, 1); 
       Log.e("Listener del switch", "Creo el helper"); 
       SQLiteDatabase db = helper1.getWritableDatabase(); 
       Log.e("Listener del switch", "obtenida la base escribible"); 
       db.execSQL(query); 
       Log.e("Listener del switch", "Query ejecutado"); 
      } 
     }); 
+1

이 과정은 잘 작동하지만, 사용자가 스위치를 켜기/끄기로 끌면 그 경우에는 clicklistener가 작동하지 않는다. :( –

1

의 getView에서 "위치"매개 변수는 무엇을 다루고 있는지 행을 알려줍니다. 다음과 같아야합니다.

final Action action = listActions.get(position); 
activa.setChecked(action.getActiva()); 
activa.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
    //you can modify Action here. 
    action.setActive(isChecked); 
    } 
}); 

다른 클래스에 데이터베이스 코드를 넣어야합니다. 그것은 당신의 코드를 더 읽기 쉽게 만들어 줄 것이다. 또한 listActions가 제대로 채워지면 데이터베이스 코드가 필요하다고 생각합니다.

또한 ViewHolder를 사용하십시오. https://www.codeofaninja.com/2013/09/android-viewholder-pattern-example.html을 참조하십시오.

+0

입니다. ViewHolder? 그게 뭐야? 스크롤 할 때 ListView에 항목이 표시되면 getView가 호출됩니다. 사용자가 화면에 이미있을 때 스위치를 클릭하면 값을 수정해야합니다. –

+0

코드는 액션의 Activa 속성 값에 따라 스위치를 켜기/끄기로 만듭니다. 사용자가 ListView에서 해당 액션 항목의 전환을 토글하는 ** ** ** 값을 변경해야합니다. –

+0

ViewHolder를 사용 했으므로 이제 스크롤이 실제로 부드럽게됩니다! 감사! 코드를 편집했습니다. 코드가 수정되었으므로 어떻게 구현합니까? –