简体   繁体   English

实施侧面导航以在活动之间切换

[英]Implementing Side Navigation to switch between activities

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. 我查看了多个示例,并从korovyansk看到了这个示例,它非常适合我想要的模型,但是当按下菜单项时,我似乎无法在活动之间切换。 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. 我通过调整“ onListItemClick”并启动新的Intent来使应用程序在活动之间进行切换,但是当活动开始时,它占用了整个屏幕,并且与侧边栏动画重叠,从而使其显得草率。 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. 我希望它在右侧导航关闭到左侧的类似Facebook的同时,在右侧的布局中加载活动。 Is there any easy way to go about doing this? 有没有简单的方法可以做到这一点?

SampleActivity.java 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 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 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 { MenuFragement.java公共类MenuFragment扩展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 ..

<?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 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. 所以我试图使用FragmentTransaction。

In MenuFragment.java under onListItemClick I have: 在onListItemClick下的MenuFragment.java中,我有:

     @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 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. 但是,它现在因错误消息而崩溃:03-22 11:54:24.469:E / AndroidRuntime(31673):java.lang.IllegalArgumentException:未找到ID为0x7f060000的片段Dummy {42540328#1 id = 0x7f060000}的任何视图关于为什么。

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). 只有一个活动的布局包含R.id.menu(菜单)和R.id.content(示例名称),然后您将使用Fragment和FragmentTransaction以及FragmentManager来操纵R.id.content中的片段(同时菜单将具有很好的动画效果)。

Furthermore I suggest you using this library for the menu: https://github.com/jfeinstein10/SlidingMenu I used it before and it works really nice. 此外,我建议您使用此库作为菜单: https : //github.com/jfeinstein10/SlidingMenu我之前使用过它,并且确实很好用。

happy coding. 快乐的编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM