不懂就问🧐apk按返回键后,重新打开,如何恢复用户之前输入的数据?
Android 基础知识,直接贴上代码,想让退出界面再次进入界面看到上次输入的内容进行回显。最简单的就是把需要回显的数据做一个文件缓存
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Map;
public class SPUtils {
private final static String spName = "Test";
public static void putValue(Context context, String key, Object value) {
SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
if (value instanceof Boolean) {
edit.putBoolean(key, (Boolean) value);
} else if (value instanceof Float) {
edit.putFloat(key, (Float) value);
} else if (value instanceof Integer) {
edit.putInt(key, (Integer) value);
} else if (value instanceof Long) {
edit.putLong(key, (Long) value);
} else if (value instanceof String) {
edit.putString(key, (String) value);
}
edit.apply();
}
public static Object getValue(Context context, String key, Object defValue) {
SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
if (defValue instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defValue);
} else if (defValue instanceof Float) {
return sp.getFloat(key, (Float) defValue);
} else if (defValue instanceof Integer) {
return sp.getInt(key, (Integer) defValue);
} else if (defValue instanceof Long) {
return sp.getLong(key, (Long) defValue);
} else if (defValue instanceof String) {
return sp.getString(key, (String) defValue);
}
return null;
}
public static void clearSP(Context context) {
context.getSharedPreferences(spName, Context.MODE_PRIVATE)
.edit()
.clear()
.apply();
}
public static void removeSP(Context context, String Key) {
context.getSharedPreferences(spName, Context.MODE_PRIVATE)
.edit()
.remove(Key)
.apply();
}
public static Map<String, ?> getAllSP(Context context) {
return context.getSharedPreferences(spName, Context.MODE_PRIVATE).getAll();
}
}
对应的活动 碎片都有 onSaveInstanceState 函数,里面的 Bundle 可以存储你想要存储的数据,然后在对应的onCreate函数提取出来即可