簡體   English   中英

切換按鈕的保存狀態

[英]Save state of toggle button

默認情況下,我在活動中將切換按鈕設置為true。 然后,當我移到同一活動中的其他片段時,切換按鈕的狀態不會改變,但是當我移至另一個活動並返回到主活動時,切換狀態將被設置回默認值。

就像默認狀態是true。 我在活動A中將其更改為false。我轉到活動B,然后返回到活動A,然后切換按鈕將再次變為true。 我希望它成為用戶設置的狀態。 有什么辦法嗎?

使用SharedPreferences ,它只是一個具有鍵值邏輯的文件,可以在上面保存一些簡單的數據。 SharedPreferences主要用於標記(視情況而定)或存儲簡單的其他設置/信息:

private static void saveToggle(Context context, boolean isToggled) {
    final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("toggle_value", isToggled).apply();
}

private static Boolean loadToggle(Context context){
    final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean("toggle_value", true);
}

希望能幫助到你。

您可以實現在后台活動中的片段重新加載時保存實例狀態的邏輯。 然后,您可以執行以下操作:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Inflate the layout for this fragment or reuse the existing one
    View view = getView() != null ? getView() : 
    inflater.inflate(R.layout.fragment_fragment2, container, false);

    return view;
}

使用它,它將檢查是否已創建該片段的早期視圖。 如果是這樣,它將重用使用infalter創建新視圖的視圖。 希望它能解決您的問題。

暫無
暫無

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

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