简体   繁体   English

Android Java onCreate

[英]Android Java onCreate

So I followed Google's first Android app sample.所以我跟着谷歌的第一个 Android 应用示例。 If I tapped the send button, it opened up the DisplayMessageActivity .如果我点击发送按钮,它会打开DisplayMessageActivity But upon tapped the back button (left arrow) from the DisplayMessageActivity, the onCreate(Bundle savedInstanceState) of the MainActivity got called again.但是在点击 DisplayMessageActivity 的后退按钮(左箭头)后, MainActivityonCreate(Bundle savedInstanceState)再次被调用。 It looks like it created a new instance of MainActivity .看起来它创建了MainActivity的一个新实例。 I could verify this by setting a bool value in onCreate of MainActivity and it was not retained.我可以通过在MainActivityonCreate中设置一个布尔值来验证这一点,并且它没有被保留。

How do you go back to the previous instance of MainActivity (the caller)?你如何 go 回到之前的MainActivity实例(调用者)?

You should have a look at Androids Activity Lifecycle .你应该看看Androids Activity Lifecycle

If you want to access the state of the activity again, I would suggest to use the method如果你想再次访问活动的state,我建议使用方法

public void onSaveInstanceState(Bundle outState)公共无效 onSaveInstanceState(捆绑 outState)

to save the current state.保存当前的 state。

Retrieve the previously saved values in this method:在此方法中检索以前保存的值:

public void onRestoreInstanceState(Bundle savedInstanceState)` public void onRestoreInstanceState(Bundle savedInstanceState)`

An example can be found here一个例子可以在这里找到

You can call finish() in the onClickListener of the back arrow view.您可以在后退箭头视图的 onClickListener 中调用 finish()。 It will finish the DisplayMessageActivity and you will return to the caller activity (MainActivity in your case).它将完成 DisplayMessageActivity 并且您将返回到调用者活动(在您的情况下为 MainActivity)。

Something like:就像是:

backArrow.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       finish();
   }
});

It looks like it created a new instance of MainActivity.看起来它创建了 MainActivity 的一个新实例。

Yes, I think, that was quite a normal behavior.是的,我认为,这是很正常的行为。

Basically, Android OS would keep only one Activity at once so that free as many memory resources as possible.基本上,Android 操作系统一次只会保留一个活动,以便尽可能多地释放 memory 资源。

You should design your application with understanding about such lifecycle concepts .您应该在了解此类生命周期概念的情况下设计您的应用程序。

You can save some of the states of your Activity in certain manners ( Parcelable , Bundle or SharedPreferences , etc.).您可以以某种方式( ParcelableBundleSharedPreferences等)保存 Activity 的某些状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM