gpt4 book ai didi

android - 如何在 onSaveInstanceState 中使用变量

转载 作者:IT老高 更新时间:2023-10-28 23:15:01 32 4
gpt4 key购买 nike

我刚开始在 android 上学习编程,但在 onSaveInstanceState 处使用变量时遇到了问题。这是我的代码:

int resultCode;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

if (savedInstanceState != null) {
super.onRestoreInstanceState(savedInstanceState);

int resultCode = savedInstanceState.getInt("resultCode");
}

Button btnOpenWithResult = (Button) findViewById(R.id.btnOpenWithResult);
btnOpenWithResult.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent myIntent = new Intent(flashlight.this, ThirdActivity.class);
startActivityForResult(myIntent, 1);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (resultCode) {
case 1:
/** option 1 */
break;
case 2:
/** option 2 */
break;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("resultCode", resultCode);
super.onSaveInstanceState(savedInstanceState);
}

我想使用 onSaveInstanceState 保存变量 resultCode 并在恢复 Activity 后再次使用它...

(对不起我的英语水平)

最佳答案

Cyren... 1) 我认为没有理由在 onCreate 中调用 super.onRestoreInstanceState。在方法中进行调用是有意义的

public void onRestoreInstanceState(Bundle saved) {
super.onRestoreInstanceState(saved);

2) 声明:

   int resultCode = savedInstanceState.getInt("resultCode");

正在“隐藏”变量:

int resultCode;

早先声明过。所以有两个版本的变量 resultCode 具有不同的范围。也许你的意思是编码:

int resultCode;

stuff here

resultCode = savedInstanceState.getInt("resultCode");

希望对您有所帮助,日航

关于android - 如何在 onSaveInstanceState 中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4701275/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com