Android Fragment handle back button press
When you are transitioning between Fragments, call addToBackStack()
as part of your FragmentTransaction
:
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();
If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener
on the parent view of your fragment:
//You need to add the following line for this solution to work; thanks skayred
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
@Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return false;
}
} );
How to detect when back button pressed in fragment android?
In your MainActivity
@Override
public void onBackPressed()
{
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();
}
How to handle Back Button press in android fragments
I think you can do this:
Create a generic Fragment:
public abstract class extends BaseFragment {
public abstract boolean onBackPressed();
}
In his Fragments, extends this BaseFragment, example:
public class TopStoriesFragment extends BaseFragment {
...
@Override
public boolean onBackPressed()
{
//if you return false, then it is because you have not consumed
//the event, but if it returns true, which is consumed by this event.
return false;
}
}
In his MainActivity activity, you should check in onBackPressed event, if the event was consumed or not, to decide what to do.
It is very important that you save the current tab!
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
//It is very important that you save the current tab!
private BaseFragment currentTab;
// ... implementation
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
currentTab = null;
switch (index) {
case 0:
// Top Rated fragment activity
currentTab = new TopStoriesFragment();
break;
case 1:
// Games fragment activity
return new NationalFragment();
case 2:
// Movies fragment activity
currentTab = new InternationalFragment();
break;
case 3:
// Movies fragment activity
currentTab = new SportsFragment();
break;
case 4:
// Movies fragment activity
currentTab = new TechnologyFragment();
case 5:
// Movies fragment activity
currentTab = new BusinessFragment();
break;
case 6:
// Movies fragment activity
currentTab = new EntertainmentFragment();
break;
}
return currentTab;
}
@Override
public int getCount() {
// get item count - equal to number of tabs
return 7;
}
public void stop() {
// get item count - equal to number of tabs
return;
}
}
@Override
public void onBackPressed()
{
//If the event returned false, then call the super.
if(currentTab == null || !currentTab.onBackPressed())
super.onBackPressed();
}
}
Change to your case!
Tap back button twice to terminate application in Fragment
I solved the problem by writing it in override fun onAttach
Please check the code below
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context as MainActivity
callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (doubleBackToExitPressedOnce) {
activity?.finish()
}
doubleBackToExitPressedOnce = true
Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
showSnackBar(
context = mContext,
layout = binding.layoutMain,
type = Constants.SnackBarTypes.Warn,
message = mContext.getString(R.string.tap_twice_to_terminate)
)
}
}
requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
Related Topics
Download Multiple Files with a Progress Bar in Listview Android
How to Add a Button to a Preferencescreen
How to Encrypt/Decrypt String in Android
Logcat Not Displaying My Log Calls
Android Studio Doesn't Recognize My Device
Offline Mode for Android App Using the Google Maps API
How to Put the Text on the Left of a Radio Button in Android
Android: Appwidget with Custom View Not Working
In What Period Does the Firebase's App Token Changes and How to Manage It
How to Block Virtual Keyboard While Clicking on Edittext in Android
Change the Right Margin of a View Programmatically
How to Start an Android Application from the Command Line
Multiple Selection in Custom Listview with Cab
Cursorloader Not Updating After Data Change
How to Use Google Login API with Cordova/Phonegap