繁体   English   中英

保存Int的值(共享首选项)

[英]Save value of Int (Shared Preference)

我是Java新手。 我做了一个计数器,当用户按住一个按钮时该计数器会上升。 我希望应用程序从其剩余位置的int值开始。 我知道SharedPreference是要走的路,但我不知道如何使用它。 我不确定将SharedPreference的哪一部分放在哪里。 谢谢。

public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button);
    text = (TextView) findViewById(R.id.textView);

    button.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
           count++;
            text.setText(String.valueOf(count));
        return false;
        }
    });

}

}

将以下功能添加到您的活动中

 public int getValue(String key) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        int value = sharedPref.getInt(key, 0);
        return value;
 }
 public void saveValue(String key, int value) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();
 }

在您的onCreate()方法中添加了一些代码

final String key = "somekey";
count  = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        count++;
        saveValue(key,count);
        text.setText(String.valueOf(count));
        return false;
    }
});

尝试转弯

int count = 1;

进入

static int count = 1;

我也是Java Noobie,所以这可能行不通。

您可以这样操作,销毁活动时在SharedPreference中保存count ,并在创建活动时从SharedPreference中读取值:

public class MainActivity extends AppCompatActivity {
    Button button;
    int count = 1;
    TextView text;
    SharedPreferences sh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        text = (TextView) findViewById(R.id.textView);

        sh = getSharedPreferences("sh_name", MODE_PRIVATE);
        count = sh.getInt("count", 1);

        button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                count++;
                text.setText(String.valueOf(count));
                return false;
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sh.edit().putInt("count", count).apply();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM