如果你想自定义按钮的行为,你必须在你的活动中使用...
@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);
}
这里是some more information关于处理关键事件。
虽然看起来你想做的只是保留你的活动状态。最好的方法是在退出之前存储您的数据,并在您重新创建活动时将其回调。
如果您想存储临时数据(我的意思是不要在两次启动之间保存),一种方法是使用sharedPreferences。
//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)
由于您不能使用 sharedPreferences(因为您不使用原始类型),另一种方法是使用全局单例。
这是一个 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; }
}
然后只需使用 ...
StorageClass.getInstance().setData1(someValue);
...和...
StorageClass.getInstance().getData1(someValue);
在 Kotlin 中 ...
object Singleton{
var data1
}
你使用的...
Singleton.data1 = someValue //Before closing.
someValue = Singleton.data1 //When restarting the activity.