Reputation: 7866
If I add a fragment from an Activity
, and then close that fragment, how am I able to track this? The issues I am running into with this scenario are the following:
Adding a fragment does not call any Activity life cycles, so I have no onPause/onResume to bail me out
I am not starting a new Activity, so starting the Activity for results isn't viable.
Any help with this would be appreciated.
Thanks in advance.
Upvotes: 0
Views: 138
Reputation: 535
package com.example.keralapolice;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
public class ChiefFragment extends Fragment {
View view;
// public OnBackPressedListener onBackPressedListener;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.activity_chief, container, false);
getActivity().getActionBar().hide();
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(getTag(), "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getActionBar().show();
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// String cameback="CameBack";
Intent i = new Intent(getActivity(), home.class);
// i.putExtra("Comingback", cameback);
startActivity(i);
return true;
} else {
return false;
}
}
});
return view;
}
}
Upvotes: 1
Reputation: 7866
As Neil mentioned, this can be done using getSupportFragmentManager().addOnBackStackChangedListener();
The implementation I did was the following:
getSupportFragmentManager().addOnBackStackChangedListener(
new android.support.v4.app.FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
int backCount = getSupportFragmentManager().getBackStackEntryCount();
// do some logic
}
});
Upvotes: 0
Reputation: 664
If you use the support version, in the AppCompatActivity
@Override
protected void onResumeFragments() {
super.onResumeFragments();
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
}
Upvotes: 2