如何保存在一个android的片段的状态呢? [英] How to save the state of an Fragment in android?

查看:166
本文介绍了如何保存在一个android的片段的状态呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只对我的片段的切换开关。什么是应用程序现在做的:用户打开应用程序,并在导航抽屉选择笔记本电脑,然后他看见一个开关(这是一个滑,它可以移动到打开或关闭......希望你明白我意思)。用户将开关至ON然后关闭该应用程序并重新打开它和开关是关闭...但它不应该是关闭...它应该是,喜欢的用户设置它,我怎么能这样做?该开关应保存其状态,用户如何选择它。
我需要的MySQL或东西吗?

I only have a switch toggle on my fragment. What is the app doing now: The user opens the app and selects "Laptop" over the navigation drawer and then he sees a switch (it is a "slider" which you can move to on or off...hope you understand what I mean). The user sets switch to ON then closes the app and reopens it and the switch is off...but it shouldn't be off...it should be on, like the user sets it How can I do that? The switch should save its state, how the user selects it. Do I need mysql or something?

(顺便说一句,我使用Android的一室公寓)

(By the way, I am using Android Studio)

我希望你明白我的意思。

I hope you understand what I mean

感谢

推荐答案

您应该使用共享preferences 来保存由切换。请尝试以下方法。

You should use SharedPreferences to save the data captured by the Switch. Try the following.

(在你的onViewCreated后初始化其他的东西)

(in your onViewCreated after you initialize your other stuff)

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();
    }
});

请参阅共享preferences 的对共享preferences和信息<一个href=\"http://developer.android.com/reference/android/widget/CompoundButton.html#setOnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener)\"相对=nofollow>这个,在交换机上的信息。

Please refer to SharedPreferences for information on SharedPreferences and this for information on the Switch.

记住,对于preference名提供的字符串是大小写敏感的,需要是相同为它获得相同的preference。

Remember that the Strings supplied for the preference names are case sensitive and need to be the same for it to get the same preference.

这篇关于如何保存在一个android的片段的状态呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆