I have an activity (MainActivity) which has a navigation drawer and can show 2 fragments (Fragments A and B), one at a time. (This activity is the default activity with navigation drawer created by android studio)
When I choose fragment B on the drawer the action bar menu is updated to show a button specific for fragment B (Button P).
Button P open an independent activity (IndependentActivity) with an explicit intent, on this activity I perform a database operation and after it I finish this activity to go back to MainActivity.
The problem is: When IndependentActivity is finished, MainActivity is shown but it shows fragment A instead of fragment B which was the one that called the intent to go to IndependentActivity.
How do I fix this by showing the fragment that initiated the action to go to another activity? Is there any way to save the fragment that was appearing?
Basically what you have to do is:
Save the state of the MainActivity when you enter IndependentActivity
Reload the state of MainActivity when you exit IndependentActivity
A simple implementation of this could be:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save which fragment that is in the view when entering another activity
savedInstanceState.putString("fragment", "fragmentB");
super.onSaveInstanceState(savedInstanceState);
}
Fragment B can be replaced with a string that tells the application which is the current fragment.
Once you come back to the activity you want to:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null ) {
// Get which fragment that was active when you left the activity
savedInstanceState.getString("fragment");
// Programatically select the fragment here
}
}
You can read more about saving instance state here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
I will leave it to you to programmatically select the fragment. I hope it helps!
I found out that I was having the same problem as this: https://stackoverflow.com/a/29464116/2325672
The back arrow to return did not work and reset the activity's fragments and the emulator back triangle worked perfectly.
Adding this code to IndependentActivity worked for me:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== android.R.id.home) {
Intent intent = NavUtils.getParentActivityIntent(this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
return true;
}
return super.onOptionsItemSelected(item);
}
Related
In my project 2 activity given - MainActivity & Second Activity.
in my main activity, I have four fragments, In the 3rd fragment, A button uses to go to the second activity.
I will implement the below code to go back
This code came back to me on MainActivity at home Fragment. but I went through the third fragment.so I want to come back to my third fragment. Please coders help me to solve this.
Also, help me when I go from fragment to fragment and want to come back to the same fragment.
In Manifest
<activity
android:name=".SecondActivity"
android:parentActivityName=".MainActivity"
android:exported="false" />
ThirdFragment
binding.goToSecondActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(getActivity(), SecondActivity.class);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
});
In Second activity
public class SecondActivity extends AppCompatActivity {
ActivitySecondBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySecondBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().setTitle("Second Page");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// code here
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
You should define a class, with a method getInstance accessible globally, that contains the last fragment visited, when you press back you should use the fragment manager to recreate the last fragment (found in the new class) and then, looking at the model of the selected fragment, repopulate it with the old data (if there are inputs/non static datas in the fragment)
I'm having an issue that maybe is happening to other community members and I wanted to ask if somebody knows the solution. I have an app with these Two activities (MainActivity, UserProfileActivity).
The MainActivity contains a NavigationDrawer that navigates through fragments. So here it's the problem. While navigating in the second fragment and pressing a button in that fragment. It opens the UserProfileActivity (child of MainActivity) with the app bar generated by being a child. When you press that back button of this new Activity it should get back to MainActivity (parent) in the fragment that we were when we called this new Activity. But not, it's getting back to the MainActivity but with the home fragment loaded. Not the one we called previously.
Does anybody know how to solve that problem? Here I leave the code of the intent I do from the fragment:
Intent intent = new Intent(context, UserProfileActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userId", message.getUserId());
intent.putExtras(bundle);
context.startActivity(intent);
Reason behind this behavior:
If you set the value of android:parentActivityName in your manifest.xml, by default pressing navigation button will create a new instance of the parent activity every time rather than popping it out from the activity backstack, so you're seeing the home fragment.
Workaround
At first, remove android:parentActivityName from manifest.xml. In onCreate method of your ChildActivity, put getSupportActionBar().setDisplayHomeAsUpEnabled(true) if you haven't already. Then override onSupportNavigateUp() of your ChildActivity, and put finish().
ChildActivity.java:
public class ChildActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
getSupportActionBar().setDisplayHomeAsUpEnabled(true)
...
}
#Override
public boolean onSupportNavigateUp() {
finish();
return super().onSupportNavigateUp();
}
}
I have an activity where the user enters some data and submits it via a submit button, that same activity also has some more buttons which lead to fragments.
When I click on the fragments, the submit button of the activity overlaps the UI of the fragment, so in the calling code of fragments I set the visibility of that submit button as invisible but when back pressed from fragment then also that submit button is invisible.
I want the submit button to be visible when activity is being displayed and invisible when the fragments are being displayed.
Add your fragment on button click,
loginSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginSubmit.setVisibility(View.GONE);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack("LayoutFragment");
ft.add(R.id.framelayoutfaqs, new LayoutFragment());
ft.commit();
}
});
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
loginSubmit.setVisibility(View.VISIBLE);
} else
super.onBackPressed();
}
NOTE : make sure you import same Fragment class which you used to create YourFragment. Also choose getSupportFragmentManager() or getFragmentManager() accordingly.
You can handle it in 0nBackPressed() method of Activity class .
Make the button invisible in either of onCreate, onActivityCreated or onAttach methods of your fragment and make it visible in onDetach method of your fragment.
How to check fragment is visible in Activity OnBackpressed
I want to check when user click back button in Searchfragment I want to set OnBackpressed is running ,but if user click back button in OtherFragment I want to set OnBackpressed is not running.
and I try this in Activity is not work
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SearchFragment searchFragment = new SearchFragment();
if (searchFragment.isVisible()){
onBackPressed();
}
}
});
thanks for your help!
First of all, when you declare something like this:
SearchFragment searchFragment = new SearchFragment();
And then call
searchFragment.isVisible()
This will obviously return false since you didnt even add it to the container. What you need to do is to retrieve the fragment instance that you already added and check it's state.
I have once tried to use the method isVisible() but it is not entirely accurate, at least not for my case. What I came up with is to check the top fragment in the container as follow:
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(fragment instance of SearchFragment) //means your visible fragment is the SearchFragment
onBackPressed();
When my MainActivity is launched my ActionBar shows the app title. Once you navigate to a fragment through the nav drawer, the title is changed to match the fragment... however, once you navigate back using the back button, the title is left untouched and still has the title of the fragment. I am looking to change it back to the application Title.
I have tried to use the onResume() method in the MainActivity.java but it appears that does not get called once you leave a fragment.
#Override
public void onResume() {
super.onResume();
// Set title
getActionBar().setTitle("FuelR");
invalidateOptionsMenu();
}
Does anyone know what the best way would be to change the title back to the app_name ?
Thanks
Indeed destroying a Fragment within an Activity doesn't mean the activity will call onResume, first you have to notice that the Fragment lives within the Activity life context, and the Fragment do not alter it's life cycle, is just part of it, what you could do is within the fragment get a reference to the activity and set the title back to previous state, as shown below:
//In Fragment
#Override
public void onDestroyView() {
super.onDestroyView();
((Cast If Necessary)getActivity()).getActionBar().setTitle("Previous Title");
}
Or a more OOP approach would be, creating an interface that declares a method setTitlePreviousText, you implement that interface in your Activity class and from the fragment you could do this:
//In Fragment
#Override
public void onDestroyView() {
super.onDestroyView();
Activity act = getActivity()
if(act instanceof SetPreviousTextInterface){
//setTitlePreviousText will be called giving you the chance to just change it back...
((SetPreviousTextInterface)act).setTitlePreviousText();
}
}
This would be the interface file:
public interface SetPreviousTextInterface{
public void setTitlePreviousText();
}
Regards!