내 Android 용 토글 버튼을 설정하고 싶지만 나중에 사용할 수 있도록 버튼 상태를 유지해야합니다. sharedPreferences를 사용하여이 작업을 수행하려고했지만 내 값은 기본 설정 파일을 반환하지만 버튼의 텍스트는 변경되지 않습니다.공유 환경 설정 및 Android 토글 버튼이 예상대로 작동하지 않습니다.
다음과 같이 테스트했습니다. tb.setChecked (false); 텍스트를 "on"에서 "off"로 변경하는 my on create의 끝에서. 하지만 내 코드를 통해 같은 효과를 얻을 수 없습니다.
무엇이 잘못 될 수 있습니까? 감사합니다. XML 내부
public SharedPreferences spref;
final String PREF_NAME = "prefrences";
public String STATE = "state_value";
ToggleButton tb;
boolean on;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tour_detail);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
Bundle b = getIntent().getExtras();
tour = b.getParcelable(".Tour");
isMyTours = b.getBoolean("isMyTours");
isFollowed = b.getBoolean("isFollowed");
Log.i(LOGTAG, "Extra passed by notif is: " + tour);
refreshDisplay();
datasource = new ToursDataSource(this);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.buttonFollow);
on = spref.getBoolean("On", true); //default is true
Log.i(LOGTAG, "VALUE for On is: " + on);
if (on = true) {
tb.setChecked(true);
} else {
tb.setChecked(false);
}
}
public void onToggleClicked(View view) {
on = ((ToggleButton) view).isChecked();
if (on) {
Toast.makeText(this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
boolean test_on = spref.getBoolean("On", true);
Log.i(LOGTAG, "VALUE for On is: " + test_on);
} else {
Toast.makeText(this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
boolean test_on = spref.getBoolean("On", true);
Log.i(LOGTAG, "VALUE for On is: " + test_on);
}
}
버튼 :
주요 코드
자바에서if (on = true) {
tb.setChecked(true);
} else {
tb.setChecked(false);
}
, 비교가 이루어집니다 :
<ToggleButton
android:id="@+id/buttonFollow"
style="?android:attr/buttonStyleSmall"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dedede"
android:textSize="12sp"
android:paddingTop="7dp"
android:paddingBottom="5dp"
android:drawableTop="@drawable/urmarire_detail_ico"
android:drawablePadding="-1sp"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
감사합니다, 지금은 매력처럼 작동합니다! 나는 좋은 몇 시간을 보냈지 만 나는이 어리석은 버그를 보지 못했다 : D –