0

How to define a Backpress Action in class thats extends Fragment implements ActionBar.TabListener, how to define a backpressed action?

1 Answers1

1

Fragments don't have an onBackPressed() callback like Activities do. You can try making your Activity maintain (or obtain) a reference to the fragment and have it call the fragment from within onBackPressed().

Fragment code:

public boolean onBackPressed() {
    // your special behavior here
    // return true if you have consumed the back press
}

Activity code:

public void onBackPressed() {
    MyFragment fragment = getFragmentManager().findFragmentById(/* some unique id*/);
    // could alternatively use findFragmentByTag() using a unique String
    if (fragment != null) {
        if (fragment.onBackPressed()) return;
    }

    // back press not consumed; allow usual behavior
    super.onBackPressed();
}
Karakuri
  • 38,365
  • 12
  • 84
  • 104
  • [See this post as well](http://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press) for more examples of the same and similar implementation – Rarw Jun 04 '13 at 20:22
  • Karakuri, i think you can help me. Iam new in android programing. I dont have an activity, my Fragment calls a class thats "extends Fragment implements ActionBar.TabListener"... So i have to do?? I have to create another javaclass for the activity?? And when do i have to call activity and when do i have to call the fragment?? My english is not good. Help please! – Afonso Matlhombe Junior Jun 04 '13 at 20:42
  • I suggest you read a lot more about Fragments on the developer site. You cannot show a fragment just by itself. A fragment is always shown in an Activity, either by including it in the layout xml file for the activity or adding it to the screen in java later on. Once you've made your Activity, override the `onBackPressed()` method as I've shown. http://developer.android.com/guide/components/fragments.html – Karakuri Jun 04 '13 at 20:51