【问题标题】:How to set radio button checked default in other activities?如何在其他活动中设置单选按钮选中默认值?
【发布时间】:2017-01-03 20:17:36
【问题描述】:

我想在登录活动中设置默认选中的单选按钮,因为用户登录时活动按钮设置自动选中,当用户进入设置活动然后更改单选按钮选择时,它会保存选择用户在设置活动中选择按钮。

代码:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       //  String radiodefault=R.id.Active;
        @Override

        public void onCheckedChanged(RadioGroup group, int checkedId) {

            // find which radio button is selected

            if(checkedId == R.id.Active) {

                Toast.makeText(getApplicationContext(), "choice: Active",

                        Toast.LENGTH_SHORT).show();
            }

            else if (checkedId == R.id.Inactive)
            {
                Toast.makeText(getApplicationContext(), "choice: Inactive",

                        Toast.LENGTH_SHORT).show();

            }
        }



    });
    active = (RadioButton) findViewById(R.id.Active);

    inactive = (RadioButton) findViewById(R.id.Inactive);

    button = (Button)findViewById(R.id.chooseBtn);

    button.setOnClickListener(new View.OnClickListener() {



        @Override

        public void onClick(View v) {

            int selectedId = radioGroup.getCheckedRadioButtonId();



            // find which radioButton is checked by id

            if(selectedId == active.getId()) {

                Toast.makeText(Settings.this,"Active is selected",Toast.LENGTH_LONG).show();

            }
            else if(selectedId == inactive.getId())
            {

                Toast.makeText(Settings.this,"Inactive is selected",Toast.LENGTH_LONG).show();

【问题讨论】:

  • 尝试使用 shareprefernce 来存储单选按钮的布尔值。并使用 SharePrefernce 设置为 Log 活动 ....

标签: android android-studio radio-button radio-group


【解决方案1】:

您可以使用SharedPreference 存储CheckBox 的值,然后在activity 重新启动时再次加载。

SharedPreferences preferences = getSharedPreferences("checkBox",MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("Active",active.isChecked());
        editor.putBoolean("InActive",inactive.isChecked());
        editor.apply();

然后在加载活动时将其检索为:

boolean isActive = preferences.getBoolean("Active",false);
boolean isInActvie = preferences.getBoolean("InActive",false);

然后您可以设置CheckBox 的当前状态,例如:

active.setChecked(isActive);
inactive.setChecked(isInActive);

【讨论】:

    【解决方案2】:

    使用 SharedPreference 将选中的存储为默认值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 2021-02-18
      • 2013-03-27
      • 1970-01-01
      • 2020-10-30
      • 2015-12-10
      • 1970-01-01
      • 2014-06-07
      相关资源
      最近更新 更多