在Activity.onstart之前调用Fragment.onstart

时间:2016-06-22 07:46:00

标签: android android-fragments fragment android-fragmentactivity android-lifecycle

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

我们可以看到我的Fragment.onStart在Activity.onStart之前被调用。任何人都知道这种行为的原因是什么?因为当Activity移动到前台时,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");
}
}

2 个答案:

答案 0 :(得分:2)

这只是因为,您正在调用super.onStart(),然后在您的活动中打印日志。所以基本上你的活动的onStart()首先运行。

我想:)

答案 1 :(得分:2)

这是正常行为。如果您需要在启动之前在片段中执行某些操作,请更好地覆盖并使用onAttach(Context context)方法。