checkbox - 在 Android Studio 中检查 Sharedpreferences 保存复选框
问题描述
我尝试按照此示例共享首选项示例 在此示例中创建 2 个复选框。我尝试了不同的方法,但它没有保存任何更改。如果单击并具有最后选择的值,我只是不想保护复选框。我是 Java 新手,希望有人能用这个例子向我解释如何解决这个问题。
package example.com.max.lschennn;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
CheckBox check1;
CheckBox check2;
public static final String mypreference = "mypref";
public static final String Name = "name";
public static final String Email = "email";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
check1 = (CheckBox) findViewById(R.id.checkBox1);
check2 = (CheckBox) findViewById(R.id.checkBox2);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.putBoolean(String.valueOf(check1), true); // Storing boolean - true/false
editor.putBoolean(String.valueOf(check2), true); // Storing boolean - true/false
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
}
解决方案
推荐阅读
- numpy - numpy.polynomial.chebyshev 中二维切比雪夫级数的系数
- android - Android:向 mipmap 图标启动器添加阴影
- javascript - 使用指令以编程方式实例化 SVG 元素
- ms-access - MS Access:从查询字段更新表字段
- postgresql - 在另一个 AWS 账户中创建 RDS/Postgres 副本?
- terraform - 如何使用带有传入变量的 terraform 导入?
- python-2.7 - 从 SQL Server 代理执行 python 脚本
- vue.js - 如何处理从 cokpit cms api 生成的多个动态路由 nuxt
- javascript - 父元素的 Kentico Cloud Delivery 过滤器
- react-native - 如何使用 react-navigation 在选项卡导航器中重置其他堆栈导航器