Java 自定义开关首选项未保存值

Java 自定义开关首选项未保存值,java,android,android-preferences,android-settings,android-switch,Java,Android,Android Preferences,Android Settings,Android Switch,当我访问PreferenceScreen时,我注意到我的自定义开关已关闭。然后我打开它并重新启动应用程序。我回到首选项屏幕,开关又关了。当我使用默认的SwitchPreference时,不会发生这种情况。我可以按我希望的方式自定义SwitchPreference,所以唯一的问题是开关值没有保存。我有四个与CustomizeSwitchPreference相关的文件,所有的首选项都放在 SettingsFragment.java public class SettingsFragment exte

当我访问PreferenceScreen时,我注意到我的自定义开关已关闭。然后我打开它并重新启动应用程序。我回到首选项屏幕,开关又关了。当我使用默认的SwitchPreference时,不会发生这种情况。我可以按我希望的方式自定义SwitchPreference,所以唯一的问题是开关值没有保存。我有四个与CustomizeSwitchPreference相关的文件,所有的首选项都放在

SettingsFragment.java

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }

}
preferences.xml:

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

    <com.example.CustomSwitchPreference
        android:key="vibration"
        android:title="vibration"
        android:summary=""
        android:defaultValue="true" />

</PreferenceScreen>
customswitch_preference.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/switch_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/switch_title"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:layout_alignParentStart="true"/>


    <Switch
        android:id="@+id/switch_pref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        />

</RelativeLayout>

MainActivity.java:

public class MainActivity extends Activity {

    private ActionBar actionBar;
    private boolean mInit = false;
    private boolean showIcon = true;
    private Menu m;
    private GridFragment gridFragment;
    private SettingsFragment settingsFragment;
    public ImageButton startButton;
    public TextView gameTimer;
    public TextView mineCount;
    public boolean isVibrating;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        settingsFragment = new SettingsFragment();
        actionBar = getActionBar();
        actionBar.setTitle("Settings");
        actionBar.setCustomView(R.layout.actionbar);
        //actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayUseLogoEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);
        //actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
        ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
        startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
        mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
        gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
        startButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        startButton.setImageResource(R.drawable.smiley2);
                        break;
                    case MotionEvent.ACTION_UP:
                        restartGame();
                        break;
                }
                return false;
            }
        });

        Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
        TextView textView;
        int[] resources =
                {R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
        for(int r: resources) {
            textView = (TextView) findViewById(r);
            textView.setTypeface(myTypeface);
        }

        if (findViewById(R.id.fragment_container) != null){
            if (savedInstanceState != null) {
                return;
            }
        }
    }

    public void restartGame() {
        startButton.setImageResource(R.drawable.smiley);
        getFragmentManager().beginTransaction().remove(gridFragment).commit();
        setText(999, gameTimer);
        startGame();
    }

    private void startGame(){

        gridFragment = new GridFragment();

        gridFragment.setArguments(getIntent().getExtras());

        getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();

    }

    public void setText(int value, TextView textView){
        value = Math.min(999,value);
        value = Math.max(-99,value);
        textView.setText(String.format("%03d",value));
    }

    @Override
    protected void onStart() {
        if (!mInit) {
            mInit = true;
            Database db = new Database(this);
            db.deleteAllSessions();
            db.close();
            startGame();
        }
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        m = menu;
        return true;
    }

    private void openSettings(){
        showIcon = false;
        gridFragment.pauseTimer();
        onPrepareOptionsMenu(m);
        actionBar.setDisplayShowCustomEnabled(false);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
        ft.hide(gridFragment);
        ft.add(android.R.id.content, settingsFragment).commit();
        //ft.replace(android.R.id.content,settingsFragment);
    }

    private void updateSettings(){

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        Map<String, ?> map = sharedPrefs.getAll();
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
        }
        isVibrating = (Boolean)map.get("vibration");
    }

    private void closeSettings(){
        showIcon = true;
        onPrepareOptionsMenu(m);
        actionBar.setDisplayShowCustomEnabled(true);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
        ft.show(gridFragment);
        ft.remove(settingsFragment).commit();
        //ft.replace(android.R.id.content,gridFragment);
        gridFragment.resumeTimer();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            openSettings();
            return true;
        }
        else if(id == R.id.backButton){
            updateSettings();
            closeSettings();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item= menu.findItem(R.id.action_settings);
        item.setVisible(showIcon);
        item = menu.findItem(R.id.backButton);
        item.setVisible(!showIcon);
        return super.onPrepareOptionsMenu(menu);
    }
}
公共类MainActivity扩展活动{
私人ActionBar ActionBar;
私有布尔mInit=false;
私有布尔showIcon=true;
私人菜单m;
私有GridFragment-GridFragment;
私人设置碎片设置碎片;
公共图像按钮开始按钮;
公共文本视图游戏计时器;
公共文本视图地雷计数;
公共卫生服务;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsFragment=新的settingsFragment();
actionBar=getActionBar();
actionBar.setTitle(“设置”);
setCustomView(R.layout.actionBar);
//actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setBackgroundDrawable(新彩色Drawable(Color.BLACK));
ViewGroup actionBarViews=(ViewGroup)actionBar.getCustomView();
startButton=(ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
mineCount=(TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
gameTimer=(TextView)actionBarViews.findViewById(R.id.topTextViewRight);
startButton.setOnTouchListener(新视图.OnTouchListener(){
@凌驾
公共布尔onTouch(视图v,运动事件){
开关(event.getAction()){
case MotionEvent.ACTION\u DOWN:
setImageResource(R.drawable.smiley2);
打破
case MotionEvent.ACTION\u UP:
重启游戏();
打破
}
返回false;
}
});
Typeface myTypeface=Typeface.createFromAsset(getAssets(),“fonts/digital-7(mono.ttf”);
文本视图文本视图;
int[]资源=
{R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
for(int r:资源){
textView=(textView)findViewById(r);
textView.setTypeface(myTypeface);
}
if(findviewbyd(R.id.fragment\u容器)!=null){
如果(savedInstanceState!=null){
回来
}
}
}
public void restartGame(){
setImageResource(R.drawable.smiley);
getFragmentManager().beginTransaction().remove(gridFragment.commit();
setText(999,游戏计时器);
startGame();
}
私有void startGame(){
gridFragment=新的gridFragment();
setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_容器,gridFragment,“gridFragment”).commit();
}
公共void setText(int值,TextView TextView){
数值=数学最小值(999,数值);
值=数学最大值(-99,值);
textView.setText(String.format(“%03d”,value));
}
@凌驾
受保护的void onStart(){
如果(!mInit){
mInit=真;
数据库db=新数据库(此数据库);
db.deleteAllSessions();
db.close();
startGame();
}
super.onStart();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(右菜单菜单菜单主菜单);
m=菜单;
返回true;
}
私有void openSettings(){
showIcon=false;
pauseTimer();
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(false);
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
ft.hide(网格碎片);
ft.add(android.R.id.content,settingsFragment.commit();
//ft.replace(android.R.id.content,settingsFragment);
}
私有void更新设置(){
SharedPreferences SharedPrefers=PreferenceManager.getDefaultSharedPreferences(此);
Map Map=sharedPrefs.getAll();
对于(Map.Entry:Map.entrySet()){
Log.d(“映射值”,entry.getKey()+”:“+entry.getValue().toString());
}
isVibrating=(布尔)map.get(“振动”);
}
私有设置(){
showIcon=true;
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(true);
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
ft.show(gridFragment);
ft.remove(settingsFragment.commit();
//ft.replace(android.R.id.content,gridFragment);
gridFragment.resumeTimer();
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
开放设置
public class MainActivity extends Activity {

    private ActionBar actionBar;
    private boolean mInit = false;
    private boolean showIcon = true;
    private Menu m;
    private GridFragment gridFragment;
    private SettingsFragment settingsFragment;
    public ImageButton startButton;
    public TextView gameTimer;
    public TextView mineCount;
    public boolean isVibrating;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        settingsFragment = new SettingsFragment();
        actionBar = getActionBar();
        actionBar.setTitle("Settings");
        actionBar.setCustomView(R.layout.actionbar);
        //actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayUseLogoEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);
        //actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
        ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
        startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
        mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
        gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
        startButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        startButton.setImageResource(R.drawable.smiley2);
                        break;
                    case MotionEvent.ACTION_UP:
                        restartGame();
                        break;
                }
                return false;
            }
        });

        Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
        TextView textView;
        int[] resources =
                {R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
        for(int r: resources) {
            textView = (TextView) findViewById(r);
            textView.setTypeface(myTypeface);
        }

        if (findViewById(R.id.fragment_container) != null){
            if (savedInstanceState != null) {
                return;
            }
        }
    }

    public void restartGame() {
        startButton.setImageResource(R.drawable.smiley);
        getFragmentManager().beginTransaction().remove(gridFragment).commit();
        setText(999, gameTimer);
        startGame();
    }

    private void startGame(){

        gridFragment = new GridFragment();

        gridFragment.setArguments(getIntent().getExtras());

        getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();

    }

    public void setText(int value, TextView textView){
        value = Math.min(999,value);
        value = Math.max(-99,value);
        textView.setText(String.format("%03d",value));
    }

    @Override
    protected void onStart() {
        if (!mInit) {
            mInit = true;
            Database db = new Database(this);
            db.deleteAllSessions();
            db.close();
            startGame();
        }
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        m = menu;
        return true;
    }

    private void openSettings(){
        showIcon = false;
        gridFragment.pauseTimer();
        onPrepareOptionsMenu(m);
        actionBar.setDisplayShowCustomEnabled(false);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
        ft.hide(gridFragment);
        ft.add(android.R.id.content, settingsFragment).commit();
        //ft.replace(android.R.id.content,settingsFragment);
    }

    private void updateSettings(){

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        Map<String, ?> map = sharedPrefs.getAll();
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
        }
        isVibrating = (Boolean)map.get("vibration");
    }

    private void closeSettings(){
        showIcon = true;
        onPrepareOptionsMenu(m);
        actionBar.setDisplayShowCustomEnabled(true);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
        ft.show(gridFragment);
        ft.remove(settingsFragment).commit();
        //ft.replace(android.R.id.content,gridFragment);
        gridFragment.resumeTimer();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            openSettings();
            return true;
        }
        else if(id == R.id.backButton){
            updateSettings();
            closeSettings();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item= menu.findItem(R.id.action_settings);
        item.setVisible(showIcon);
        item = menu.findItem(R.id.backButton);
        item.setVisible(!showIcon);
        return super.onPrepareOptionsMenu(menu);
    }
}