2011-10-10 8 views
22

Tengo una lista y una casilla de verificación en cada fila. Quiero que cada vez que hago clic en una fila, la casilla cambie su estado en consecuencia.Cambiar el estado de CheckBox en el elemento de la lista, haga clic en?

checkbox.xml

<CheckBox 
    android:id="@+id/CheckBox" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:focusable="false" 
    android:text="" /> 

detector de clics de mi lista

protected void onListItemClick(ListView l, View v, int position, long id) { 
    Toast.makeText(getApplicationContext(), "You have selected item no." 
      + (position + 1) + "", Toast.LENGTH_SHORT).show(); 

    super.onListItemClick(l, v, position, id); 
    selectedRow = position; 

    if (v == null) { 
     LayoutInflater lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = lif.inflate(R.layout.posting_detail_question_row, null); 
    } 

    if (checkedTextView.isChecked()) { 
     Toast.makeText(getApplicationContext(), "Already voted", 
       Toast.LENGTH_SHORT).show(); 
    } else { 
     String[] from = {"option", "votes"}; // values to fetch from 
     // hashmap 
     int[] to = {R.id.option, R.id.votes}; // id's for the view 

     SimpleAdapter adp = new SimpleAdapter(getApplicationContext(), 
       hashList, R.layout.posting_detail_question_row, from, to); 
     setListAdapter(adp); 
     checkedTextView.setChecked(true); 
    } 
} 

posting_detail_question_row.xml

<?xml version="1.0" encoding="UTF-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="40dp" 
    android:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     android:background="@drawable/poll_border_top_bg" 
     android:orientation="horizontal"> 

     <TextView 
      android:id="@+id/option" 
      android:layout_width="0dp" 
      android:layout_height="fill_parent" 
      android:layout_marginLeft="10dp" 
      android:layout_weight=".3" 
      android:gravity="center_vertical" 
      android:text="Answer 1" 
      android:textColor="#333333" 
      android:textSize="15sp" /> 

     <TextView 
      android:id="@+id/votes" 
      android:layout_width="0dp" 
      android:layout_height="fill_parent" 
      android:layout_marginLeft="10dp" 
      android:layout_weight="1" 
      android:gravity="center_vertical" 
      android:textColor="#333333" 
      android:textSize="15sp" /> 

     <CheckBox 
      android:id="@+id/CheckBox" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:focusable="false" 
      android:text="" /> 
    </LinearLayout> 
</LinearLayout> 

Mi adaptador es un SimpleAdapter:

SimpleAdapter adp = new SimpleAdapter(getApplicationContext(), 
      hashList, R.layout.posting_detail_question_row, from, to); 
    Log.v("MyLog", "after simple adapter"); 
    setListAdapter(adp); 
+1

post aquí su código de diseño posting_detail_question_row.xml –

+0

pago y envío este http://www.vogella.de/articles/AndroidListView/ article.html # overview_listview –

+0

@ P M- Paresh Mayani comprobar ahora señor –

Respuesta

39

Es necesario utilizar findViewById para obtener un puntero a su casilla de verificación:

protected void onListItemClick(ListView l, View v, int position, long id) { 

    Toast.makeText(getApplicationContext(), "You have selected item no." 
       +(position+1)+"", Toast.LENGTH_SHORT).show(); 

    super.onListItemClick(l, v, position, id); 

    if (v != null) { 
     CheckBox checkBox = (CheckBox)v.findViewById(R.id.Checkbox); 
     checkBox.setChecked(!checkBox.isChecked()); 
    } 
} 

Si está recibiendo el evento de clic a continuación v nunca debería ser nulo, pero he puesto los controles apropiados.

+0

Merlin esto no funciona, señor, muestra un error de tiempo de ejecución ... volveré a formular mi pregunta ... quiero que cuando haga clic en cualquier r ow de la lista, la casilla de verificación debe marcarse en consecuencia –

+0

Vi un pequeño error que debería haber sido 'R.ID.Checkbox' pero estoy seguro de que descubrió que ... puede ver el logcat y ver cuál es el error – Merlin

+0

@ Merlin su respuesta, sin embargo, me dio una idea genial que me falta, es decir, la parte (v! = null) pero todavía estoy atascado, si lo hago de acuerdo con usted mi problema se resolvió pero funciona cuando hago clic dos veces porque mi adaptador se creó en el cláusula else y falta la casilla de verificación ... he actualizado el código ¿puedes mirarlo y darme un consejo ... gracias por la respuesta, aunque ... –

2
CheckBox checkBox = (CheckBox) v.findViewById(R.id.CheckBox); 
checkBox.setChecked(true); 
+0

no funciona señor –

+0

Muchas gracias: D @ –

7

Dentro de la onListItemClick hacer esto:

CheckBox cb = (CheckBox) v.findViewById(R.id.CheckBox); 
cb.setChecked(!cd.isChecked()); 
0

Aquí está el código completo, puede añadir este después de ajustar el addapter:

list.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 


     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

      String message = "Item " + position; 
      Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); 

      CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox); 
      cb.setChecked(!cb.isChecked()); 


     } 


    }); 
Cuestiones relacionadas