且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

片段:按下返回按钮时调用哪个回调 &定制它

更新时间:2023-12-03 07:57:10

Question 1: See http://developer.android.com/reference/android/app/Fragment.html#Lifecycle:

"As a fragment is no longer being used, it goes through a reverse series of callbacks:

onPause() - fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.

onStop() - fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.

onDestroyView() - allows the fragment to clean up resources associated with its View.

onDestroy() - called to do final cleanup of the fragment's state.

onDetach() - called immediately prior to the fragment no longer being associated with its activity."

Question 2: If you must know that it was the back button specifically that is triggering the callbacks, You can capture the back button press in your Fragment's Activity and use your own method to handle it:

public class MyActivity extends Activity
{
    //...
    //Defined in Activity class, so override
    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        myFragment.onBackPressed();
    }
}

public class MyFragment extends Fragment
{
    //Your created method
    public void onBackPressed()
    {
        //Handle any cleanup you don't always want done in the normal lifecycle
    }
}