Question

The problem is that I can't access slidingMenu(defined in header) from current Activity after onBackPressed on previous Activity.

I have this fragment that should be included as a header in more screens(Activity):

class HeaderFragment extends Fragment{
  private static SlidingMenu slidingMenu;

  public void onActivityCreated(Bundle savedInstanceState){
     super.onActivityCreated(savedInstanceState);
     context=getActivity();

     slidingMenu = new SlidingMenu(context);
     ...
     slidingMenu.attachToActivity(context, SlidingMenu.SLIDING_CONTENT);
     ...
     menuButton = (Button)getView().findViewById(R.id.menuButton);
     menuButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          slidingMenu.toggle();
        }
      });
      ....
}

here is header_fragment.xml :

...
<LinearLayout
   android:layout_width="40dp"
   android:layout_height="match_parent"
   android:layout_gravity="left" >

   <Button
       android:id="@+id/menuButton"
       ...
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="left"
       android:layout_weight="0" />
</LinearLayout>

Here is fragment inclusion in activity's layout:

<fragment
    android:name="com.HeaderFragment"
    android:id="@+id/headerFragment"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp" />

And in each activity I have onBackPressed:

public class ManyActivities extends FragmentActivity {
   ...
   @Override
   public void onBackPressed() {
      //here I need slidingMenu from header
      if (slidingMenu.isMenuShowing())
         slidingMenu.toggle();
      else
         super.onBackPressed();
   }
}
Was it helpful?

Solution

Just one question .. are you using the slidingMenu library to simulate a menu that slides out from the left or right of the screen? if that is the fact then dont :)

Google has added something to the framework called Drawer Navigation which is exactly that and it handles the back button press for you so when the drawer is open and you press back then it closes the menu and if its not open it will do a normal back. That is handled as part of the framework that is supplied for you.

you get this functionality by using a DrawerLayout as your activity's layout http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top