java 如何在Android应用程序中保存复选框状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25261296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:42:24  来源:igfitidea点击:

How to save a checkbox state in android app

javaandroidcheckbox

提问by user3932803

I have this app with a simple checkbox which adds a line to build.prop when the user presses it , the thing works but when i exit the app the check box is reseted , is there a way to prevent this with adding a sample code in your post because i am still newbie to android apps.

我有一个带有简单复选框的应用程序,当用户按下它时,它会在 build.prop 中添加一行,这一切正常,但是当我退出应用程序时,复选框被重置,有没有办法通过添加示例代码来防止这种情况发生您的帖子,因为我仍然是 Android 应用程序的新手。

MainActivity.java

主活动.java

package com.mythi.tests;

import java.io.DataOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainActivity extends Activity {

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

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

    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onCheckboxClicked(View view) {
        // Is the view now checked?
        boolean checked = ((CheckBox) view).isChecked();

        // Check which checkbox was clicked
        switch(view.getId()) {
            case R.id.checkBox1:
                if (checked){
                    try{
                        Process su = Runtime.getRuntime().exec("su");
                        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                        outputStream.writeBytes("cp /system/build.prop /system/build.prop.bak\n");
                        outputStream.writeBytes("echo 'persist.sys.scrollingcache=3' >> /system/build.prop\n");
                        outputStream.flush();

                        outputStream.writeBytes("exit\n");
                        outputStream.flush();
                        su.waitFor();
                    }catch(IOException e){

                    }catch(InterruptedException e){

                    }
        }else{
            try{
                Process su = Runtime.getRuntime().exec("su");
                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

                outputStream.writeBytes("rm -r /system/build.prop\n");
                outputStream.writeBytes("mv /system/build.prop.bak /system/build.prop\n");
                outputStream.flush();

                outputStream.writeBytes("exit\n");
                outputStream.flush();
                su.waitFor();
            }catch(IOException e){

            }catch(InterruptedException e){

            }   
            break;
        } 

       }

   }

}

activity_main.xml

活动_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mythi.tests.MainActivity" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="169dp"
        android:onClick="onCheckboxClicked"
        android:text="CheckBox" />

</RelativeLayout>

回答by 0101100101

Where did you get this extremely odd approach using getRuntime().exec()? Here's an easy working code sample for you using SharedPreferences. Replace your whole switch-statement with this one:

你从哪里得到这种使用 getRuntime().exec() 的非常奇怪的方法?这是使用 SharedPreferences 的简单工作代码示例。用这个替换你的整个 switch 语句:

switch(view.getId()) {
case R.id.checkBox1:
    PreferenceManager.getDefaultSharedPreferences(this).edit()
        .putBoolean("checkBox1", checked).commit();
    break;
}

Inside onCreate() add this:

在 onCreate() 中添加:

CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
boolean checked = PreferenceManager.getDefaultSharedPreferences(this)
    .getBoolean("checkBox1", false);
checkBox1.setChecked(checked);

Done.

完毕。

回答by Jithu

You can save the value in a preference and bind the value when it loads. for example,

您可以将值保存在首选项中,并在加载时绑定该值。例如,

boolean checkedFlag = Preference.getBoolean("checkboxstate",false);
    CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
    cb.setChecked(checkedFlag);

For setting values in preference

用于设置优先值

SharedPreferences Preference = getSharedPreferences("pref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = Preference.edit();
editor.putBoolean("checkboxstate", checkboxstate);
editor.commit();

retrive value like

检索价值,如

SharedPreferences Preference = getSharedPreferences("pref", Activity.MODE_PRIVATE);
 boolean isCheckboxSet = Preference.getBoolean("checkboxstate");

回答by nobalG

Yes, you can Just save the value of checkBox state in SharedPreferences and then retrieve them later when required

是的,您可以将 checkBox 状态的值保存在 SharedPreferences 中,然后在需要时检索它们

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("state", "checked");
editor.commit();

later you can get it like

稍后你可以得到它

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
 String str = sp.getString("state");


.See How to use SharedPreferences in Android to store, fetch and edit values

.参见 如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值



You can use putBoolean()and getBoolean()methods of Sharedpreferencestoo as checkboxeshave only two states

您也可以使用putBoolean()getBoolean()方法,Sharedpreferences因为checkboxes只有two states