簡體   English   中英

如何在Android中保存Fragment的狀態?

[英]How to save the state of an Fragment in android?

我的片段上只有一個切換開關。 該應用程序現在正在做什么:用戶打開該應用程序並在導航抽屜上選擇“筆記本電腦”,然后他看到一個開關(它是一個“滑塊”,您可以將其打開或關閉...希望您理解我的意思)意思)。 用戶將開關設置為“開”,然后關閉該應用程序,然后重新打開它,然后開關處於關閉狀態……但不應關閉……應將其打開,就像用戶將其設置為該如何操作? 交換機應保存其狀態,以及用戶如何選擇它。 我需要mysql之類的東西嗎?

(順便說一句,我正在使用Android Studio)

我希望你明白我的意思

謝謝

嘗試使用共享首選項保存應用程序數據,當應用程序再次啟動時,應用程序可以將數據保存在共享首選項中,它可以再次從共享首選項中加載數據...希望能有所幫助:)

您應該使用SharedPreferences保存Switch捕獲的數據。 嘗試以下方法。

(在初始化其他內容后,在onViewCreated中)

Switch mySwitch = (Switch) findViewById(R.id.mySwitch); // or however else you want to initialize it
final String SWITCH_BOOLEAN = "switchBoolean";
final String PREFERENCE_NAME = "sharedPreferenceFile";
final SharedPreferences prefs = getActivity().getSharedPreferences(PREFERENCE_NAME, 0); // change the name to what you want, this is an xml file that stores your preferences
final SharedPreferences.Editor prefsEditor = prefs.getEditor();

mySwitch.setChecked(prefs.getBoolean(SWITCH_BOOLEAN, false); //also change this name to what you want.

mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        prefsEditor.putBoolean(SWITCH_BOOLEAN, isChecked);
        prefsEditor.apply();
    }
});

請參考SharedPreferences對SharedPreferences和信息這個交換機上的信息。

請記住,為首選項名稱提供的字符串區分大小寫,並且必須相同,才能獲得相同的首選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM