samedi 3 janvier 2015

Android how to call method from layout with vairables

I may be going about this the wrong way - applying what I know from other API's - so, if so, perhaps you can point me to a different direction. The fact is, I can't seem to find any examples for exactly what I am doing. I'm trying to call a method from the xml layout. I want to call the same method from various checkboxes, basically on a click of any checkbox, I want to store the isChecked state in the SharedPreferences file. This is my xml and java:



<CheckBox
android:layout_width="194dp"
android:layout_height="wrap_content"
android:text="@string/Chri"
android:id="@+id/chkbxChristmas"
android:checked="false"
android:onClick="savePreferencesData(@string/Chri,@+id/chkbxChristmas)"/>


public void savePreferencesData(String preference,int id) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
CheckBox cb1 = (CheckBox) findViewById(id);
editor.putBoolean(preference, cb1.isChecked());

// Commit the edits!
editor.commit();

};


As you can see, I'm trying to pass the checkbox ID and the @string/Chri string value (I use this value as the tag in the SharedPreferences file) so the method knows which preference to update.


Is it even possible to pass the variables, and is there a better way to identify which checkbox is calling the method?


I appreciate the help!





Aucun commentaire:

Enregistrer un commentaire