Does this Fragment equal this Fragment - android

So I am updating an existing old app and trying to make it more Material and more up to date.
A key area of the old app had a 'wizard' type of interface which would be a chain of Activities where the user could add Parcelable data and move forwards and backwards through the wizard using either a UI back button or the Android back button.
I've updated to Fragments all over the app and, as Google say to not have a UI back button, I am relying on the default back button.
As the default back button doesn't register for Fragments, I am trying to implement something along the lines of the solution at Vinsol
This kind of works, but I need to identify what Fragment used the back button so that I can decide what to do. This is the handler in the main Activity:
#Override
public void onBackPressed() {
if(selectedFragment == null ) {
//this isn't a Fragment we need to handle
super.onBackPressed();
}else if(selectedFragment == myFragmentOne){
//do something here for that fragment
//before going back
}else if(selectedFragment == myFragmentTwo){
//do something here for that fragment
//before going back
}
}
The null handler works ok because I set selectedFragment to null on the Fragments I'm not interested in any special handling.
But selectedFragment is either null or a Fragment. How can I check if selectedFragment is myFragmentOne or myFragmentTwo? There are no Tags to check against.

Check in this manner using instanceOf
if ( selectedFragment instanceof CustomFragmentClass) {
//put UR code
}

Related

Detecting the visible fragment in android

I want to implement the onbackpressed() in android and my code is as follows
public void backpressed(){
NDListeningFragment fragment1=(NDListeningFragment)getSupportFragmentManager().findFragmentByTag(ConnectedDevicesFragment.TAG);
if(fragment1!=null && fragment1.isVisible())
{
super.onBackPressed();
}
else
{
fragment1=(NDListeningFragment)SimpleFragmentFactory.createFragment(ConnectedDevicesFragment.TAG);
getSupportFragmentManager().beginTransaction().replace(R.id.content,fragment1).commit();
fragment1.setUserVisibleHint(true);
}
}
The above code checks if the visible fragment is ConnectedDevicesFragment. If yes then super() is called and if not then I create ConnectedDevicesFragment and replace it in the framelayout.
But I am not able to implement in this way. When I press back button it reloads the Connected DevicesFragment again and again.
can you help with some workaround.
Cheers!
You creates fragment1 object every time in the onBackPressed function it means it will not null and it is on invisible state. You need to add NDListeningFragment in backstack when you open NDListeningFragment first and check Is the fragment available in back stack. If yes then call super.onBackpressed.

Recreate Fragments on BackKey Pressed

Im trying to Solve a problem where when a user press back key, the fragment should be recreated rather than loading from back stack. I have a single Main activity with a frame layout and i replace the fragments within the single frame dynamically. the code below works when the user go from fragment within fragment. but when the user select from navigation drawer, the replaced fragment is going on to the top of backstack which is causing problems.
Right now the code i wrote in BackKey Pressed Event
public override void OnBackPressed()
{
Android.Support.V4.App.FragmentManager.IBackStackEntry entry =
SupportFragmentManager.GetBackStackEntryAt(SupportFragmentManager.BackStackEntryCount - 1);
string str = entry.Name;
if (SupportFragmentManager.BackStackEntryCount == 0)
{
this.Finish();
}
else
{
Fragment fr = (Fragment)MagicallyCreateInstance(str);
SupportFragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, fr).Commit();
SupportFragmentManager.PopBackStack();
}
base.OnBackPressed();
}
i also have a replace fragment method which i use to replace fragments. but in this process the back key is getting disabled by default somehow (Not sure how) but whenever there is existing fragment in the backstack, the old UI is getting loaded. Can i refresh the layout here?
public void ReplaceFragment(Fragment fragment, FragmentManager fragmentManager)
{
string backStateName = fragment.Class.SimpleName;
bool fragmentPopped = fragmentManager.PopBackStackImmediate(backStateName, 0);
if (!fragmentPopped && fragmentManager.FindFragmentByTag(backStateName) == null)
{
fragmentManager.BeginTransaction()
.Replace(Resource.Id.content_frame, fragment).SetTransitionStyle(FragmentTransaction.TransitFragmentFade)
.AddToBackStack(backStateName)
.Commit();
}
}
Can anyone please help me solve this any one of the above?
I hope I'm understanding your problem correctly. But it sounds like you want to make sure that when the user selects a destination from your main navigation you want to make sure the back stack is cleared or reset.
Ex:
Stack looks like this:
A->B->C
User selects D from main navigation, stack should look like:
D
NOT
A->B->C->D
If this is the case, you should clear the back stack before navigating to any top-level destinations. This can be done like so:
FragmentManager.PopBackStack(null, FragmentManager.PopBackStackInclusive);
The documentation for this method is not great, but it will pop everything off the back stack. A discussion can be found here: https://groups.google.com/d/msg/android-developers/0qXCA9rW7EI/M9riRM0kl9QJ

savedInstanceState null when using navigateUpFromSameTask

I'm new to Android development, and what I playing around with is a sports type app with a app flow like: League -> Team -> Player -> Player stats (this is in a ViewPager). All using Fragments.
I have the flow working in this direction, but I'm trying to use home button to navigate back up the stack (back button works too). My problem is that going forward through the flow I pass the ID of the League, then Team, then Player, etc... But when the home button is pressed, this data is no longer available.
I've tried setting retainInstance to true, but that doesn't do it. Not sure why, but the ID fields are all null in onCreate whenever I press back or the home button.
I've also tried overriding onSaveInstance and onActivityCreated, and putting the ID's for each entity in the bundle there, but even though I save the ID in the bundle in onSaveInstance, the bundle is null in onActivityCreated.
How can I keep the ID's of each entity around for when the user hits the back or home buttons?
Thanks for any help.
I had a similar problem when I add the Settings Activity.
I had to modify the onMenuItemSelected created automatically.
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
// I removed this line
//NavUtils.navigateUpFromSameTask(this);
// and add this 3 lines
Intent intent = NavUtils.getParentActivityIntent(this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
navigateUpFromSameTask() not only set the FLAG_ACTIVITY_CLEAR_TOP flag. It also clears the savedInstanceState.
I solved this issue by storing the values that goes normaly in saveInstanceState in SharedPreferences. Storing them in onPause() and restoring in onResume().

Android - How can i return the current fragment after onActivityResult()?

I have an activity that have some buttons and some fragments.
If I click on button A, i'll show Fragment "FragA". When I'm in "FragA", I can perform some actions like choose a picture from gallery and I need to stay in "FragA" after choose picture.
But when I choose picture, I return to Activity and "FragA" is hidden.
How can perform an action and still in same Fragment or display correct fragment in Activity?
You can recreate fragment again and replace it in your Activity with using modification of this code:
if (currentState == STATE_MAIN_FRAGMENT) {
return;
}
mainScreenFragment = (MainScreenFragment) getSupportFragmentManager().findFragmentByTag(MainScreenFragment.TAG);
if (mainScreenFragment == null) {
mainScreenFragment = new MainScreenFragment();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flFragmentContainer, mainScreenFragment, MainScreenFragment.TAG);
fragmentTransaction.commit();
First "if" checks if the fragment is set or not. It is not required but it's a good practice. It prevents you from replacing fragment when it is not necessary.
And there is one thing strange for me. Because you said <<"FragA" is hidden>> - that means it was already set but container is not visible? Then yourFragmentContainer.setVisiblity(View.VISIBLE); in on Activity result.
And the last thing that could help you is to retain the fragment so it won't be ever destroyed and recreated again. Some helpful links:
Understanding Fragment's setRetainInstance(boolean)
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
Or you can just copy-paste what is in your Button's OnClickListener so it happens onActivityResult too.

How do I get the back button to go to a certain Fragment in horizontal scrolling? Exits app right now

the title pretty much explains it.
I have horizontal scrolling set up, the first screen has buttons to the other Fragments as well as the whole horizontal scroll system. What I would like is for the user to be able to press the back button when on one of these fragments and for the app to return to the first screen with all the buttons.
From there I want the back button to be an AlertDialog asking the user if they would like to exit the app. At the moment this is what is happening (On all Fragments when you press the back button the AlertDialog I created pops up).
I've looked into Fragment transactions and "addToBackStack()" but I don't know how to implement it. I've looked at the dev guide and certain questions on this site but getting one or two lines of code doesn't help in implementing it.
I have a FragmentActivity with a FragmentPagerAdapter set up and each Fragment has its own Java file. I have 5 Fragments that are all called in the FragmentActivity and FragmentPagerAdapter.
I don't think I need to show you guys any of my code for the moment since it's all set up in the normal manner. Please let me know if you do though.
The bit of code I found on other questions and one in particular was the following:
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();
It's a bit hard to go on just that though.
I would really appreciate your help.
EDIT: my code removed - wasn't needed.
If you use the ViewPager from your question which I answered earlier and you want to come back to the first fragment of the ViewPager when the user presses the BACK button then override the onBackPressed method like this:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("outDialog") != null
&& ((DialogFragment) getSupportFragmentManager()
.findFragmentByTag("outDialog")).isVisible()) {
// we have the out dialog visible and the user clicked back so let
// the
// normal events happen
super.onBackPressed();
return;
}
int currentPosition = mViewPager.getCurrentItem();
if (currentPosition != 0) {
// if the page the ViewPager shows isn't the first one then move it
// to the first one
mViewPager.setCurrentItem(0);
} else {
// we are at the first position already and the user wants out, so
// annoy him with a dialog that asks him once again if he wants out.
DialogFragment askHim = new DialogFragment();
askHim.show(getSupportFragmentManager(), "outDialog");
// in the dialog listener, if the user presses ok, finish the activity
}
}
did you try to override Activity.onBackPressed() ?
I used addToBackStack() and it works well, but I have no idea whether it works with PagerAdapter.
I think you can override Activity.onBackPressed() and in that method, you can check whether current page is front page or not and do whatever job you want to do.
Here are pseudo code that I think.
public void onBackPressed() {
if( pager.getCurrentPage() == 0 ) { //I'm not sure this method exists or not. just example. :-)
//exit code here
} else {
// show first page
}
}

Categories

Resources