gpt4 book ai didi

android - 如何手动调用 onSaveInstanceState()

转载 作者:行者123 更新时间:2023-11-29 01:09:20 29 4
gpt4 key购买 nike

我正在编写一个程序,我在同一个 Activity 中调用多个布局,但后来我注意到当我切换布局时,切换之前所做的更改不会恢复并且 onSavedInstanceState(Bundle outState) 是没有叫。我已尝试手动调用该方法,但无法获取 Bundle outState

所以真正的问题是:我如何获取和存储要在我选择的时间调用和/或恢复的 Activity 的当前状态?

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
// more code
}

@Override
public void onBackPressed() {
if (layoutId == R.layout.activity_contact_view) exit();
else if (layoutId == R.layout.main) {
Toast.makeText(NsdChatActivity.this, "Successful back button action", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_contact_view);
refreshContactList();
}
}

然后从一个单独的类

public void updateList(final int found) {
LinearLayout layxout = (LinearLayout) ((Activity)mContext).getWindow().getDecorView().findViewById(R.id.others);
TextView t = new TextView(mContext);
t.setClickable(true);
t.setText(found + ". " + activity.sNames.get(found));
t.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
t.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//show chat view
activity.setContentView(R.layout.main);
TextView name = (TextView)activity.findViewById(R.id.clientName);
name.setText(activity.sNames.get(found).split(" \\(")[0]);
final ScrollView scroll = (ScrollView)activity.findViewById(R.id.scroll);
scroll.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
});
layxout.addView(t);
}

最佳答案

我可能会迟到,但你可以做的是保持你作为类(class)成员的状态。这样您就可以随时恢复状态。

Bundle mState;

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state
savedInstanceState = mState;
super.onSaveInstanceState(savedInstanceState);
}
@Overrite
public void onRestoreInstanceState(Bundle savedInstance){
mState = savedInstance;
Restore();
}

public void Restore(){
//access your state and restore
}

此外,您不应该使用 setContentView 在 View 之间切换,这是一种昂贵的方式。您可能想查看 ViewSwitcherViewFlipper或者以某种方式实现 Fragments。

关于android - 如何手动调用 onSaveInstanceState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425049/

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