Finishing current activity from a fragment

前端 未结 11 1513
野的像风
野的像风 2020-12-13 02:02

I have a fragment in an activity that I am using as a navigation drawer. It contains buttons that when clicked start new activities (startActivity from a fragment simply ca

11条回答
  •  时光取名叫无心
    2020-12-13 02:18

    As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.

    Code below is a snippet from an activity and fragment which has a save and cancel button.

    PlayerActivity

    public class PlayerActivity extends Activity 
        implements PlayerInfo.PlayerAddListener {
    
        public void onPlayerCancel() {
           // Decide if its suitable to close the activity, 
           //e.g. is an edit being done in one of the other fragments?
           finish();
        }
    }
    

    PlayerInfoFragment, which contains an interface which the calling activity needs to implement.

    public class PlayerInfoFragment extends Fragment {
       private PlayerAddListener callback; // implemented in the Activity
    
       @Override
       public void onAttach(Activity activity) {
         super.onAttach(activity);
         callback= (PlayerAddListener) activity;
       }
    
       public interface PlayerAddListener {
           public void onPlayerSave(Player p); // not shown in impl above
           public void onPlayerCancel();
       }
    
       public void btnCancel(View v) {
          callback.onPlayerCancel(); // the activity's implementation
       }
    }
    

提交回复
热议问题