toolbar配合DrawerLayout实现酷炫的菜单滑动效果

如果你有在关注一些遵循最新的Material Design设计规范的应用的话(如果没有,假设你有!),也许会发现有很多使用了看起来很舒服、很高大上的侧滑菜单动画效果,示例如下(via 参考2):这里写图片描述

今天就来使用官方支持库来快速实现这类效果,需要使用到Toolbar和DrawerLayout,详细步骤如下:(如果你还不知道这两个Widget,先自己Google吧~)

1.首先需要添加appcompat-v7支持

如果是在Android Studio 1.0 RC4上创建的项目,默认已经添加了appcompat-v7支持了,如果不是最新版AS则需要在build.gradle中添加如下代码:

dependencies {
...//其他代码
compile 'com.android.support:appcompat-v7:21.0.2'
}

添加完成后需要同步一下gradle

2.添加Toolbar

由于Toolbar是继承自View,所以可以像其他标准控件一样直接主布局文件添加Toolbar,但是为了提高Toolbar的重用效率,可以在layout创建一个custom_toolbar.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/tl_custom"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar">
   /android.support.v7.widget.Toolbar>

说明:

android.support.v7.widget.Toolbar - 当然如果只在Lollipop中可以直接使用Toolbar而不需要加上v7支持

xmlns:app - 自定义xml命名控件,在AS中可以直接指定res-auto而不需要使用完整包名

android:background 和 android:minHeight 均可以在styles.xml中声明

2.添加DrawerLayout

和Toolbar类似,为了提高代码重用效率,可以在layout中创建一个custom_drawerlayout.xml代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dl_left"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<!--主布局-->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/iv_main"
        android:layout_width="100dp"
        android:layout_height="100dp" />
</LinearLayout>
<!--侧滑菜单-->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:layout_gravity="start">
    <ListView
        android:id="@+id/lv_left_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"
        android:text="DrawerLayout" />
</LinearLayout>
  </android.support.v4.widget.DrawerLayout>

Drawerlayout标签中有两个子节点,一个是左边菜单,一个是主布局,另外需要在左边菜单起始位置设置为android:layout_gravity=”start”

3.实现activity_main.xml

         <LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
    <!--Toolbar-->
    <include layout="@layout/custom_toolbar" />
    <!--DrawerLayout-->
    <include layout="@layout/custom_drawerlayout" />
</LinearLayout>

直接使用include标签,简洁明了

4.完善Java代码

public class MainActivity extends ActionBarActivity {
//声明相关变量
private Toolbar toolbar;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView lvLeftMenu;
private String[] lvs = {"List Item 01", "List Item 02", "List Item 03", "List Item 04"};
private ArrayAdapter arrayAdapter;
private ImageView ivRunningMan;
private AnimationDrawable mAnimationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViews(); //获取控件
    //京东RunningMan动画效果,和本次Toolbar无关
    mAnimationDrawable = (AnimationDrawable) ivRunningMan.getBackground();
    mAnimationDrawable.start();
    toolbar.setTitle("Toolbar");//设置Toolbar标题
    toolbar.setTitleTextColor(Color.parseColor("#ffffff")); //设置标题颜色
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //创建返回键,并实现打开关/闭监听
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            mAnimationDrawable.stop();
        }
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            mAnimationDrawable.start();
        }
    };
    mDrawerToggle.syncState();
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    //设置菜单列表
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lvs);
    lvLeftMenu.setAdapter(arrayAdapter);
}
private void findViews() {
    ivRunningMan = (ImageView) findViewById(R.id.iv_main);
    toolbar = (Toolbar) findViewById(R.id.tl_custom);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_left);
    lvLeftMenu = (ListView) findViewById(R.id.lv_left_menu);
}
}

5.当然比较重要还有styles.xml和colors.xml,具体如下

<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!--状态栏颜色-->
    <item name="colorPrimaryDark">@color/Indigo_colorPrimaryDark</item>
    <!--Toolbar颜色-->
    <item name="colorPrimary">@color/Indigo_colorPrimary</item>
    <!--返回键样式-->
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>
    </style>
    <style name="AppTheme.DrawerArrowToggle" parent="Base.Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>
</resources>
 <?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Indigo_colorPrimaryDark">#303f9f</color>
<color name="Indigo_colorPrimary">#3f51b5</color>
<color name="Indigo_nav_color">#4675FF</color>
</resources>

到此就实现了高大上菜单侧滑,最终效果如下(注:在Yosemite上貌似直接Record手机屏幕貌似不起作用,而且动画由于帧率原因无法实时,就先这样看吧~)
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.zhy.view; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.zhy.ccbCricleMenu.R; public class CircleMenuLayout extends ViewGroup { /** * layout的半径 */ private int mRadius; private float mMaxChildDimesionRadio = 1 / 4f; private float mCenterItemDimesionRadio = 1 / 3f; private LayoutInflater mInflater; private double mStartAngle = 0; private String[] mItemTexts = new String[] { "安全中心 ", "特色服务", "投资理财", "转账汇款", "我的账户", "信用卡" }; private int[] mItemImgs = new int[] { R.drawable.home_mbank_1_normal, R.drawable.home_mbank_2_normal, R.drawable.home_mbank_3_normal, R.drawable.home_mbank_4_normal, R.drawable.home_mbank_5_normal, R.drawable.home_mbank_6_normal }; private int mTouchSlop; /** * 加速度检测 */ private float mDownAngle; private float mTmpAngle; private long mDownTime; private boolean isFling; public CircleMenuLayout(Context context, AttributeSet attrs) { super(context, attrs); mInflater = LayoutInflater.from(context); for (int i = 0; i < mItemImgs.length; i++) { final int j = i; View view = mInflater.inflate(R.layout.turnpalte_inner_view, this, false); ImageView iv = (ImageView) view .findViewById(R.id.id_circle_menu_item_image); TextView tv = (TextView) view .findViewById(R.id.id_circle_menu_item_text); iv.setImageResource(mItemImgs[i]); tv.setText(mItemTexts[i]); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), mItemTexts[j], Toast.LENGTH_SHORT).show(); } }); addView(view); } mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight()); // 获得半径 mRadius = Math.max(getWidth(), getHeight()); final int count = getChildCount(); // Log.e("TAG", count + ""); int childSize = (int) (mRadius * mMaxChildDimesionRadio); int childMode = MeasureSpec.EXACTLY; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } int makeMeasureSpec = -1; if (child.getId() == R.id.id_circle_menu_item_center) { makeMeasureSpec = MeasureSpec.makeMeasureSpec( (int) (mRadius * mCenterItemDimesionRadio), childMode); } else { makeMeasureSpec = MeasureSpec.makeMeasureSpec(childSize, childMode); } child.measure(makeMeasureSpec, makeMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int layoutWidth = r - l; int layoutHeight = b - t; int layoutRadius = Math.max(layoutWidth, layoutHeight); // Laying out the child views final int childCount = getChildCount(); int left, top; int radius = (int) (layoutRadius * mMaxChildDimesionRadio); float angleDelay = 360 / (getChildCount() - 1); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getId() == R.id.id_circle_menu_item_center) continue; if (child.getVisibility() == GONE) { continue; } mStartAngle %= 360; float tmp = layoutRadius * 1f / 3 - 1 / 22f * layoutRadius; left = layoutRadius / 2 + (int) Math.round(tmp * Math.cos(Math.toRadians(mStartAngle)) - 1 / 2f * radius); top = layoutRadius / 2 + (int) Math.round(tmp * Math.sin(Math.toRadians(mStartAngle)) - 1 / 2f * radius); // Log.e("TAG", "left = " + left + " , top = " + top); child.layout(left, top, left + radius, top + radius); mStartAngle += angleDelay; } View cView = findViewById(R.id.id_circle_menu_item_center); cView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), "you can do something just like ccb ", Toast.LENGTH_SHORT).show(); } }); // Log.e("TAG", // cView.getMeasuredWidth() + " , " + cView.getMeasuredWidth()); int cl = layoutRadius / 2 - cView.getMeasuredWidth() / 2; int cr = cl + cView.getMeasuredWidth(); cView.layout(cl, cl, cr, cr); } private float mLastX; private float mLastY; private FlingRunnable mFlingRunnable; // @Override // public boolean onTouchEvent(MotionEvent event) // { // } @Override public boolean dispatchTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastX = x; mLastY = y; mDownAngle = getAngle(x, y); mDownTime = System.currentTimeMillis(); mTmpAngle = 0; if (isFling) { removeCallbacks(mFlingRunnable); isFling = false; return true ; } break; case MotionEvent.ACTION_MOVE: float start = getAngle(mLastX, mLastY); float end = getAngle(x, y); // Log.e("TAG", "start = " + start + " , end =" + end); if (getQuadrant(x, y) == 1 || getQuadrant(x, y) == 4) { mStartAngle += end - start; mTmpAngle += end - start; } else { mStartAngle += start - end; mTmpAngle += start - end; } // rotateButtons((float) (mStartAngle - currentAngle)); requestLayout(); mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: float anglePrMillionSecond = mTmpAngle * 1000 / (System.currentTimeMillis() - mDownTime); Log.e("TAG", anglePrMillionSecond + " , mTmpAngel = " + mTmpAngle); if (Math.abs(anglePrMillionSecond) > 230 && !isFling) { post(mFlingRunnable = new FlingRunnable(anglePrMillionSecond)); } if(Math.abs(anglePrMillionSecond) >230 || isFling) { return true ; } break; } return super.dispatchTouchEvent(event); } private float getAngle(float xTouch, float yTouch) { double x = xTouch - (mRadius / 2d); double y = yTouch - (mRadius / 2d); return (float) (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI); } private int getQuadrant(float x, float y) { int tmpX = (int) (x - mRadius / 2); int tmpY = (int) (y - mRadius / 2); if (tmpX >= 0) { return tmpY >= 0 ? 4 : 1; } else { return tmpY >= 0 ? 3 : 2; } } private class FlingRunnable implements Runnable { private float velocity; public FlingRunnable(float velocity) { this.velocity = velocity; } public void run() { if ((int) Math.abs(velocity) < 20) { isFling = false; return; } isFling = true; // rotateButtons(velocity / 75); mStartAngle += (velocity / 30); velocity /= 1.0666F; postDelayed(this, 30); requestLayout(); Log.e("TAG", velocity + ""); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值