简体   繁体   中英

Fragment.onstart is being called before Activity.onstart

MMuzammil: MainActivity:in onCreate
MMuzammil: FirstFragment:in onAttach
MMuzammil: FirstFragment:in onCreate
MMuzammil: FirstFragment:in onCreateView
MMuzammil: FirstFragment:in onActivityCreated
MMuzammil: FirstFragment:in onStart <----
MMuzammil: MainActivity:in onStart <----
MMuzammil: MainActivity:in onResume
MMuzammil: FirstFragment:in onResume

As we can see my Fragment.onStart is being called before Activity.onStart. Any one knows what can be the cause of this behaviour? Because when Activity is moving to the foreground, Activity's callback methods should always call first

Activity:

public class MainActivity extends AppCompatActivity {

public static final String TAG = "MMuzammil";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(TAG, "MainActivity:in onCreate");
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new FirstFragment()).commit();
}

@Override
protected void onStart() {
    super.onStart();
    Log.d(TAG, "MainActivity:in onStart");
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "MainActivity:in onResume");
}

@Override
protected void onPause() {
    super.onPause();
    Log.d(TAG, "MainActivity:in onPause");
}

@Override
protected void onStop() {
    super.onStop();
    Log.d(TAG, "MainActivity:in onStop");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "MainActivity:in onDestroy");
}

@Override
protected void onRestart() {
    super.onRestart();
    Log.d(TAG, "MainActivity:in onRestart");
}
}

It just because, you are calling super.onStart() and then printing logs in your activity. So basically the onStart() of your activity is running first.

I guess :)

It's normal behavior. If you need to do something in fragment before starting, better override and use onAttach(Context context) method.

I have the same problem. When I try to start my service in Fragment.onStart() I get a crash because activity has not been started yet.

I add this to my Fragment.onStart() :

override fun onStart() {
    super.onStart()
    launch {
        requireActivity().lifecycle.withStarted {
            // do work
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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