使用 SharedPreferences 的菜单中的单选按钮

Radio Buttons in Menu using SharedPreferences

尝试将三个单选按钮显示为菜单项,用户只需选择一个,即使关闭应用程序也会保存该选择。然后,他们选择的选项将用于确定应用启动时将显示哪个布局片段。

不太了解如何在共享首选项中保存用户选择,因为我以前从未使用过它并且是编码新手。

我的菜单布局是

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/settings"
    android:title="@string/settings">
    <menu >
        <group android:id="@+id/startScreenGroup" android:checkableBehavior="single">
            <item android:id="@+id/submenu0" android:title="Fragment 0" />
            <item android:id="@+id/submenu1" android:title="Fragment 1" />
            <item android:id="@+id/submenu2" android:title="Fragment 2" />
        </group>
    </menu>
</item>

</menu>

您的无线电组需要一个在用户单击项目时触发的回调。在该回调中,您可以将点击的值保存到 SharedPreference.

  1. 在你的 Activity 的 onCreate() 方法中,找到你的 RadioGroup 并给它分配一个 OnCheckedChangedListener.
  2. 在侦听器 onCheckChanged() 方法中,检查用户单击了哪个项目。
  3. 使用 SharedPreferences.Editor 将其保存到磁盘。

您的代码将如下所示(未编译或测试):

public void onCreate(final Bundle savedInstanceBundle) {

    final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.startScreenGroup);
    radioGroup.setOnChangedListener(new RadioGroup.OnChangedListener() {
        @Override
        void onCheckedChanged(RadioGroup group, int checkedId) {
            SharedPreferences.Editor editor = getPreferenceManager().getSharedPreferences().edit();
            switch (checkedId) {
                case R.id.submenu0:
                    editor.putString("my_key", "menu0");
                    break;
                case R.id.submenu1:
                    editor.putString("my_key", "menu1");
                    break;
                case R.id.submenu2:
                    editor.putString("my_key", "menu2");
                    break;
            }
            editor.commit();        
        }
    });

}

试试下面的代码,它没有经过测试,但基本上这就是它通常的样子,如果在尝试我的代码时出现任何错误,请告诉我。

private RadioGroup radioGroup;
private RadioButton radioButton;

//Fragment references
private Fragment0 fragment0;
private Fragment1 fragment1;
private Fragment2 fragment2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_detail);

        //Create a SharedPreference variable
        SharedPreferences appPreferences = this.getSharedPreferences("YOUR APP PACKAGE NAME", Context.MODE_PRIVATE);


        final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.startScreenGroup);
       radioGroup.setOnChangedListener(new RadioGroup.OnChangedListener() {

          @Override
         void onCheckedChanged(RadioGroup group, int checkedId) {

            switch (checkedId) {

            case R.id.submenu0:
                 appPreferences.edit().putString("LoadFragment","submenu0");
                 break;
            case R.id.submenu1:
                 appPreferences.edit().putString("LoadFragment","submenu1");
                 break;
            case R.id.submenu2:
                appPreferences.edit().putString("LoadFragment","submenu2");
                break;
             }

        appPreferences.commit();        
    }
});


        //get menuID
        String fragmentToLoad = appPreferences.getString("LoadFragment","");

       //load user selected fragment
       if(fragmentToLoad != null){

       switch(fragmentToLoad){
          case "submenu0" : 
          this.getSupportFragmentManager().beginTransaction()
              .replace(R.id.container_main, fragment0)
              .commit();
              break;

         case "submenu1" : 
         this.getSupportFragmentManager().beginTransaction()
             .replace(R.id.container_main, fragment1)
             .commit();
             break;

         case "submenu2" : 
         this.getSupportFragmentManager().beginTransaction()
             .replace(R.id.container_main, fragment2)
             .commit();
              break;
        }
   }


}

更新

我终于有时间来处理这个问题,100% 在 2 部手机(Lollipop 和 Marshmallow 设备)上工作和测试。

public class MainActivity extends AppCompatActivity {

    SharedPreferences appPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Create a SharedPreference variable
        appPreferences = this.getSharedPreferences("com.example.ramithrd.radiobuttonssharedpref", Context.MODE_PRIVATE);

        //get menuID
        String fragmentToLoad = appPreferences.getString("LoadFragment","");

        //load user selected fragment
        if(fragmentToLoad != null){

            switch(fragmentToLoad){
                case "submenu0" :
                    this.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container_main, new Fragment0())
                            .commit();
                    break;

                case "submenu1" :
                    this.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container_main, new Fragment1())
                            .commit();
                    break;

                case "submenu2" :
                    this.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container_main, new Fragment2())
                            .commit();
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.submenu0) {
            appPreferences.edit().putString("LoadFragment","submenu0").commit();
            this.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container_main, new Fragment0())
                    .commit();

        } else  if (id == R.id.submenu1) {
            appPreferences.edit().putString("LoadFragment","submenu1").commit();
            this.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container_main, new Fragment1())
                    .commit();
        } else if (id == R.id.submenu2){
            appPreferences.edit().putString("LoadFragment","submenu2").commit();
            this.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container_main, new Fragment2())
                    .commit();
        }


        return super.onOptionsItemSelected(item);
    }
}