Question

So I'm trying to implement side navigation in my app and I can't seem to find a way to implement it the way I want. I have been looked at multiple examples and I came accross this one from korovyansk that pretty much fits the mold that I would like, however I can't seem to switch between activities when a menu item is pressed. I got the app to switch between activities by tweaking the "onListItemClick" and starting a new Intent, but when the activity starts it takes up the whole screen and overlaps the sidebar animation thus making it look sloppy. I want it to load the activity in the layout on the right while the side nav is closing to the left kind of like facebook. Is there any easy way to go about doing this?

SampleActivity.java

public class SampleActivity extends FragmentActivity {

@TargetApi(11)
@Override

public void onCreate(Bundle savedInstanceState) {
    int poss;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.sample);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        getActionBar().hide();
    }
    findViewById(R.id.sample_button).setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
                    SlideoutActivity.prepare(SampleActivity.this, R.id.inner_content, width);
                    startActivity(new Intent(SampleActivity.this,
                            MenuActivity.class));
                    overridePendingTransition(0, 0);
                }
            });
}


}

MenuActivity.java

public class MenuActivity extends FragmentActivity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSlideoutHelper = new SlideoutHelper(this);
    mSlideoutHelper.activate();
    getSupportFragmentManager().beginTransaction().add(com.korovyansk.android.slideout.R.id.slideout_placeholder, new MenuFragment(), "menu").commit();
    mSlideoutHelper.open();
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
        mSlideoutHelper.close();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}


public SlideoutHelper getSlideoutHelper(){
    return mSlideoutHelper;
}

private SlideoutHelper mSlideoutHelper;


}

SlideoutHelper.java

public class SlideoutHelper {

private static Bitmap sCoverBitmap = null;
private static int sWidth = -1;

public static void prepare(Activity activity, int id, int width) {
    if (sCoverBitmap != null) {
        sCoverBitmap.recycle();
    }
    Rect rectgle = new Rect();
    Window window = activity.getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    int statusBarHeight = rectgle.top;

    ViewGroup v1 = (ViewGroup) activity.findViewById(id).getRootView();
    v1.setDrawingCacheEnabled(true);
    Bitmap source = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);
    if (statusBarHeight != 0) {
        sCoverBitmap = Bitmap.createBitmap(source, 0, statusBarHeight, source.getWidth(), source.getHeight() - statusBarHeight);
        source.recycle();
    } else {
        sCoverBitmap = source;
    }
    sWidth = width;
}

public SlideoutHelper(Activity activity) {
    this(activity, false);
}

public SlideoutHelper(Activity activity, boolean reverse) {
    mActivity = activity;
    mReverse = reverse;
}

public void activate() {
    mActivity.setContentView(R.layout.slideout);
    mCover = (ImageView) mActivity.findViewById(R.id.slidedout_cover);
    mCover.setImageBitmap(sCoverBitmap);
    mCover.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            close();
        }
    });
    int x = (int) (sWidth * 1.2f);
    if (mReverse) {
        @SuppressWarnings("deprecation")
        final android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, x, 0);
        mActivity.findViewById(R.id.slideout_placeholder).setLayoutParams(lp);
    } else{
        @SuppressWarnings("deprecation")
        final android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 0, 0);
        mActivity.findViewById(R.id.slideout_placeholder).setLayoutParams(lp);
    }
    initAnimations();
}

public void open() {
    mCover.startAnimation(mStartAnimation);
}

public void close() {
    mCover.startAnimation(mStopAnimation);
}

protected void initAnimations() {
    int displayWidth = ((WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
    final int shift = (mReverse ? -1 : 1) * (sWidth - displayWidth);
    mStartAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0,
            TranslateAnimation.ABSOLUTE, -shift,
            TranslateAnimation.ABSOLUTE, 0,
            TranslateAnimation.ABSOLUTE, 0
            );

    mStopAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0,
            TranslateAnimation.ABSOLUTE, shift,
            TranslateAnimation.ABSOLUTE, 0,
            TranslateAnimation.ABSOLUTE, 0
            );
    mStartAnimation.setDuration(DURATION_MS);
    mStartAnimation.setFillAfter(true);
    mStartAnimation.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            mCover.setAnimation(null);
            @SuppressWarnings("deprecation")
            final android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, -shift, 0);
            mCover.setLayoutParams(lp);
        }
    });

    mStopAnimation.setDuration(DURATION_MS);
    mStopAnimation.setFillAfter(true);
    mStopAnimation.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            mActivity.finish();
            mActivity.overridePendingTransition(0, 0);
        }
    });
}

private static final int DURATION_MS = 400;
private ImageView mCover;
private Activity mActivity;
private boolean mReverse = false;
private Animation mStartAnimation;
private Animation mStopAnimation;
}    

MenuFragement.java public class MenuFragment extends ListFragment {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, new String[] { " First", " Second", " Third", " Fourth", " Fifth", " Sixth"}));
    getListView().setCacheColorHint(0);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);


     ((MenuActivity)getActivity()).getSlideoutHelper().close();

}


}

xml..

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg_android" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="45dip"
    android:paddingLeft="2dip"
    android:paddingRight="2dip"
    android:background="#bb000000">

    <Button style="@android:style/Widget.Button.Small"
        android:id="@+id/sample_button"
        android:layout_width="35dip"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dip"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:text=">" />

    <TextView android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/sample_button"
        android:layout_centerVertical="true"
        android:textSize="19sp"
        android:textColor="#ffffff"
        android:text="Facebook-like slide-out nav"/>
</RelativeLayout>

slideout.xml

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

<FrameLayout
    android:id="@+id/slideout_placeholder"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#777777"/>


<ImageView
    android:id="@+id/slidedout_cover"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitXY" />

</AbsoluteLayout>

Edit: Ok was trying to avoid that but it does seem inevitable now. So im trying to use FragmentTransaction.

In MenuFragment.java under onListItemClick I have:

     @Override
     public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);


     ((MenuActivity)getActivity()).getSlideoutHelper().close();
     Fragment dummy = new Dummy();
     FragmentTransaction transaction = getFragmentManager().beginTransaction();

     // Replace whatever is in the fragment_container view with this fragment,
     // and add the transaction to the back stack
     transaction.replace(R.id.inner_content, dummy);
     transaction.addToBackStack(null);

     // Commit the transaction
     transaction.commit();
}

Dummy.java

public class Dummy extends Fragment{
 View blag;
 @TargetApi(11)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                      Bundle savedInstanceState) {

   blag = inflater.inflate(R.layout.samplex, container, false);
  //(samplex is same as sample.xml just different logo
  return blag;
}



}

However it's now crashing with the error message:03-22 11:54:24.469: E/AndroidRuntime(31673): java.lang.IllegalArgumentException: No view found for id 0x7f060000 for fragment Dummy{42540328 #1 id=0x7f060000} Any idea on why that is.

Était-ce utile?

La solution

It's a simple answer:

Do not use Activities!

There will be only one activity with a layout containing R.id.menu (the menu) and R.id.content (example names) then you'll use Fragment and FragmentTransaction and the FragmentManager to manipulate fragments inside R.id.content (whilst the menu will animate nicely).

Furthermore I suggest you using this library for the menu: https://github.com/jfeinstein10/SlidingMenu I used it before and it works really nice.

happy coding.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top