如何不破坏onBackPressed中的活动



我需要在调用onBackPressed方法时,活动不会被破坏,而是暂停和停止。

我的想法是,它的工作原理就像按下手机的Home按钮时一样,它调用onPauseonStop,因为这样,活动不会被破坏,当活动重新打开时,onResume会被调用,这样变量就会保持活动关闭时的值。

有办法做到这一点吗?如果没有,是否有一种方法可以在活动结束后保持变量的状态?我曾尝试使用SharedPreference,但我无法使用它们,因为我的变量与提供的变量类型不同。

如果你想自定义按钮的行为,你必须在你的活动中使用。。。

@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);
}

以下是有关处理关键事件的更多信息。


尽管看起来你想做的只是保持你的活动状态。最好的方法是在退出前存储数据,并在重新创建活动时调用数据。

如果你想存储临时数据(我的意思是不要在两次引导之间保存它(,一种方法是使用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);

在科特林

object Singleton{
var data1
}

您使用的。。。

Singleton.data1 = someValue    //Before closing.
someValue = Singleton.data1    //When restarting the activity.

最新更新