Get back to a fragment from an Activity

前端 未结 10 1898
野趣味
野趣味 2020-12-09 05:10

I have three fragment in an Activity C. they are behaving as tabs. I have to go from a fragment to a new Activity X. Now i want to come back to fragment from Activity X.

相关标签:
10条回答
  • 2020-12-09 05:47

    In the activity you have started from your fragment, you can do the following:

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            //do whatever you want here
            finish();
            return true;
        }
    

    That works for me :)

    0 讨论(0)
  • 2020-12-09 05:47

    This code works in my case. I just make an Onclick method to the button . the code is below:I made onclick method clickForFriends in Button and Id is backFriendsList, And I use android.support.v4.app.Fragment class. This method should take back from new Activity to the fragment from the Activity was launched and this method should be in the Activity after the onCreate method

     public void clickedForFriends(View v){
        if (v.getId() == R.id.backFriendsList){
           onBackPressed();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 05:48

    when you start an activity from a fragment, the fragment never got killed, you can simply come back to your fragment by kill the current activity by finish();, it just like when from a fragment you open an activity and on pressing back button you jumped to the fragment without losing data.

    0 讨论(0)
  • 2020-12-09 05:54

    Simplest way :

    @Override
    onBackPressed(){
    finish();
    }
    
    0 讨论(0)
  • 2020-12-09 05:57

    You can start the activity that you are navigating to using startActivityForResult() and then while coming back to the previous activity you set the result.In the activity that you are coming back to,show the fragment depending on the resultcode. You can accomplish this task by hiding all the fragments that you dont want to show. This can work even if you are going to another activity from another fragment.

    0 讨论(0)
  • 2020-12-09 06:05

    You can add a TAG (A string name for the fragment basically) and then load the fragment using findFragmentByTag().

    Google documentation for findFragmentByTag() is here.

    Or you can also addToBackStack() while calling the fragment from FragmentTransaction, doc link here. from google docs:

    "By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button."

    0 讨论(0)
提交回复
热议问题