无法在“设置”活动中关闭

9o685dep  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(205)

我想在模拟器中关闭switchpreference,但当我按下时,它将保持在“on”状态。我放了一个onchangelistener,所以当有更改时,我可以更改另一个类中的值。我也在我的智能手机上测试了它,但当我按下时,它会保持在sampe“开”的位置。这是我的设置活动代码

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            SharedPreferences abcd = PreferenceManager.getDefaultSharedPreferences(getContext());

               boolean checkzent = abcd.getBoolean("zentriert", false);

            if(checkzent)
            {
                MapsActivity.zentriertmap = true;

            }

            else
            {
                MapsActivity.zentriertmap = false;
            }

            SwitchPreferenceCompat check = (SwitchPreferenceCompat) findPreference("zentriert");

            check.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object obj) {
                    boolean yes = (boolean) obj;
                    if(yes)
                    {
                        MapsActivity.zentriertmap = true;

                    }
                    else
                    {
                        MapsActivity.zentriertmap = false;
                    }

                    return false;
                }
            });

        }
    }

}

这是我的xml文件:

<PreferenceScreen
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <PreferenceCategory
        app:title="Karte">

        <SwitchPreferenceCompat
            app:key="zentriert"
            app:title="Karten Zentrierung"
            app:defaultValue="true"
            />

        <SeekBarPreference

        app:key ="seekbar"
        app:defaultValue="16"
        app:min="2"

        app:title="Karte Zoomlevel" />

    </PreferenceCategory>

</PreferenceScreen>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题