11
votes

Comment faire quelque chose quand une case à cocher change d'état?

Ceci est mon code:

    <CheckBox
        android:id="@+id/sprint_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/sprint_game" />

    <CheckBox
        android:id="@+id/marathon_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/marathon" />

    <CheckBox
        android:id="@+id/never_ending_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/never_ending" />


3 commentaires

"" J'ai essayé d'utiliser ".setonCheckedChangelistener", mais je ne peux pas faire ça "" Pourquoi tu ne peux pas faire ça? Placez le code de votre SetonCheckedCHangelistener


L'auditeur de changement enregistré est le moyen de faire de quoi vous parlez.


Pourquoi ne pas utiliser de bouton radio. (c'est-à-dire un groupe de radio). C'est exactement pourquoi ceux-ci sont faits. L'utilisation ne peut pic que l'un, pas besoin de désactiver les deux autres. Et à la manière dont oncheckChangedlistener fonctionne aussi sur les boutons radio.


3 Réponses :


29
votes

Ceci est la façon dont vous êtes notifié sur les modifications cochées:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    switch(buttonView.getId()){
               case R.id.sprint_checkbox:
                 //do stuff
               break;
               case R.id.marathon_checkbox:
                 //do stuff
               break;
               case R.id.never_ending_checkbox:
                //do stuff
               break;

            }

}


1 commentaires

Merci. Votre code a résolu mon problème tout en obtenant des valeurs booléennes de la case à cocher.



1
votes

Je crois qu'un radiobutton serait plus approprié pour vos objectifs.

public void onRadioButtonClick(View v) {
    RadioButton button = (RadioButton) v;
    // DO YOUR THING HERE DEPENDING ON WHICH RADIOBUTTON IS PICKED
}


0 commentaires

1
votes
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    int id = buttonView.getId();

    if(isChecked){
       switch(id){
          case R.id.sprint:
          //add to database
          ...
       }
    }
    else{
      switch(id){
          case R.id.sprint:
          //remove from database
          ...
       }
   }
}
This should allow you to with ID's. Hope it works.

0 commentaires