如果你想定制你的按钮的行为,你必须在你的活动中使用...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
return true; //To assess you have handled the event.
//If you want the normal behaviour to go on after your code.
return super.onKeyDown(keyCode, event);
Here is 一些更多的信息关于处理关键事件。
尽管看起来你想做的只是保留你的活动的状态。最好的方法是在退出前存储你的数据,并在你重新创建你的活动时将其调回来。
如果你想存储临时数据(我的意思是在两次启动之间不保存它),一种方法是使用共享偏好.
//Before your activity closes
private val PREFS_NAME = "kotlincodes"
private val SAVE_VALUE = "valueToSave"
val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putInt(SAVE_VALUE, value)
editor.commit()
//When you reopen your activity
private val PREFS_NAME = "kotlincodes"
val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
sharedPref.getString(SAVE_VALUE, null)
Another way to do it since you cannot use 共享偏好 (because you don't use primitive types), is to use a global singleton.
这里有一个Java实现...
public class StorageClass{
private Object data1 = null;
private StorageClass instance;
private StorageClass(){};
public static final StorageClass getInstance(){
if(instance == null){
synchronized(StorageClass.class){
if(instance==null) instance = new StorageClass();
return instance;
public void setData1(Object newData) { data1 = newData; }
public Object getData1() { return data1; }
Then just use ...
StorageClass.getInstance().setData1(someValue);
...和...
StorageClass.getInstance().getData1(someValue);
In Kotlin ...
object Singleton{
var data1