onBackPressed() and Fragments
the problem is that Fragment
does not have public void onBackPressed()
method.
you are getting the error because your method is annotated with @Override
but it is not actually overriding any method in the superclass. the purpose of @Override
is exactly this one, letting you know that you think you're overriding something but, actually, you aren't
on a side note, what you are trying to do is unnecessary. if you press the back button and you have fragments in the back stack they will be popped automatically. try this
public class FragmentsActivity extends AppCompatActivity {
public static class FragmentA extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = new TextView(getActivity());
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
view.setBackgroundColor(0xffff0000);
return view;
}
}
public static class FragmentB extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = new TextView(getActivity());
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
view.setBackgroundColor(0xff00ff00);
return view;
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.add(R.id.fragment_container, new FragmentA(), FragmentA.class.getSimpleName())
.commit();
// notice addToBackStack here
fm.beginTransaction()
.add(R.id.fragment_container, new FragmentB(), FragmentB.class.getSimpleName())
.addToBackStack(FragmentB.class.getSimpleName())
.commit();
}
}
Using onBackPressed() in Android Fragments
Why don't you want to use the back stack? If there is an underlying problem or confusion maybe we can clear it up for you.
If you want to stick with your requirement just override your Activity's onBackPressed() method and call whatever method you're calling when the back arrow in your ActionBar gets clicked.
EDIT: How to solve the "black screen" fragment back stack problem:
You can get around that issue by adding a backstack listener to the fragment manager. That listener checks if the fragment back stack is empty and finishes the Activity accordingly:
You can set that listener in your Activity's onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
}
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;
}
} );
Related Topics
Should The Call to The Superclass Method Be The First Statement
Calling Camera from an Activity, Capturing an Image and Uploading to a Server
How to Set Proxysettings and Proxyproperties on Android Wi-Fi Connection Using Java
Invalid Heap Address and Fatal Signal 11
Handle Screen Orientation Changes When There Are Asynctasks Running
Show Popup Above Map Marker in Mapview
How to Enable Cookies in Android Webview
Gradle Warning: Variant.Getoutputfile() and Variant.Setoutputfile() Are Deprecated
Can't Resolve Android Databinding Class
Loop Through All Subviews of an Android View
Android API 23 Change Navigation View Headerlayout Textview
Register Receiver in a Service
Stuck with Gradle Build Running
How to Use Percentage for Android Layout
Android V21 Theme.Appcompat Color Accent Is Ignored, No Padding on Dialogs