Si se selecciona o no un botón de conmutación

Bueno, estoy tratando de ver si una casilla está marcada o no, pero tengo errores.

Definición del código de casilla de verificación:

public class Preferences extends PreferenceActivity { CheckBoxPreference togglePref; ... } 

Código CheckBox:

 public void checkNotify() { if (togglePref.isChecked()==(true)) { ... } } 

OnCreate código:

  protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //SharedPreferences settings = getSharedPreferences("EasySettingsPreferences", MODE_PRIVATE); //boolean notify = settings.getBoolean("notify", false); checkNotify(); rootView = new LinearLayout(this); rootView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); rootView.setOrientation(LinearLayout.VERTICAL); togglePref = new CheckBoxPreference(this); textView = new TextView(this); textView.setText(R.string.app_name); titleView = new LinearLayout(this); titleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 26)); titleView.setBackgroundResource(R.drawable.pattern_carbon_fiber_dark); titleView.addView(textView); preferenceView = new ListView(this); preferenceView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); preferenceView.setId(android.R.id.list); PreferenceScreen screen = createPreferenceHierarchy(); screen.bind(preferenceView); preferenceView.setAdapter(screen.getRootAdapter()); rootView.addView(titleView); rootView.addView(preferenceView); this.setContentView(rootView); setPreferenceScreen(screen); 

}

Imagen de Logcat:

Logcat pic http://img710.imageshack.us/img710/8529/unledxq.png

Imagen del depurador

Debugger pic http://img847.imageshack.us/img847/1192/unled1rn.png

Por favor ayúdame si puedes. ¡Gracias!

En su método onCreate() , está llamando a checkNotify() antes de que togglePref se haya inicializado. Desea mover esa inicialización hacia arriba (o mover checkNotify() hacia abajo.)

Supongo que nunca inicializar togglePref . Para estar seguro que necesitamos ver el onCreate() . (Voy a actualizar mi respuesta si mi suposición estaba mal …)

Editar Tenía razón. Usted llama a checkNotify() antes de que incluso se inicialice la variable togglePref . Compruebe su lógica si realmente tiene sentido llamar a ese método antes de todo lo demás o si está bien si lo llama más tarde.

Un consejo: puede simplificar su declaración if:

 // yours: if (togglePref.isChecked()==(true)) { // simplified: if (togglePref.isChecked()) { 
  • Cambiar el botón utilizando dos imágenes en diferentes estados
  • Cómo cambiar el color de fondo del botón de alternar en Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.