Android仿qq侧滑菜单

我们经常能看到各种app中都有应用侧滑菜单(SlidingMenu),效果很好的一种显示方式,今天我就向大家展示可以说是很简单就能实现和qq的侧滑菜单很相似的效果。现在侧滑菜单的框架在github上也有很多,有兴趣的可以去搜一下,今天我就给大家展示一个简单的仿qq侧滑菜单的例子。

开始

实现原理

我们可以自定义一个view,然后用一个水平滚动条HorizontalScrollView匹配父容器

原理如图:
qq_menu原理

要有这个HorizontalScrollView要有两倍屏幕的宽度,用这个Android自带的水平滚动条来实现左右滑动的效果。是不是很简单呢。原理就是这么简单。下面我将我的代码贴出来,大家可以参考,或修改。

部分实现代码

首先我们生成一个自定义view 继承HorizontalScrollView

SlidingMenu.java

public class SlidingMenu extends HorizontalScrollView {

    private LinearLayout mWapper;
    private ViewGroup mMenu;
    private ViewGroup mContent;
    private int mScreenWidth;

    private int mMenuRightPadding = 50;

    private boolean once = false;

    private boolean isOpen;

    private int mMenuWidth;

这样就自动帮我们生成了一个自定义view所必须的方法
如果不需要使用自定义属性,那么我们需要修改一下两个方法如下:

    /**
     * 未使用自定义属性时调用
     *
     * @param context
     * @param attrs
     */
    public SlidingMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public SlidingMenu(Context context) {
        this(context, null);
    }

如果使用自定义属性,在本例中将会调用如下方法

    /**
     * 当使用了自定义属性时,会调用此构造方法
     *
     * @param context
     * @param attrs
     * @param defStyle
     */
    public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SlidingMenu, defStyle, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.SlidingMenu_rightPadding:
                    mMenuRightPadding = a.getDimensionPixelOffset(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 50, context.getResources().getDisplayMetrics()));
                    break;
            }
        }
        a.recycle();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mScreenWidth = outMetrics.widthPixels;
    }

其中需要在res/values/下新建一个xml文件为attr.xml,添加适当的代码后如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>


    <declare-styleable name="SlidingMenu" >
        <attr name="rightPadding" format="dimension"></attr>
    </declare-styleable>
</resources>

其中的rightPadding为水平滚动条向右边滑动到极限后保留的距离(原谅我语言匮乏,不怎么会形容),还是不能理解我说的什么意思的话可以自己看看手机qq的效果

定义view的大小

我们为了让水平滚动条要适配屏幕的大小,所以得定义一下view的宽和高和自身的宽高

    /**
     * 设置子view的宽和高
     * 设置自己的宽和高
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (!once) {
            mWapper = (LinearLayout) getChildAt(0);
            mMenu = (ViewGroup) mWapper.getChildAt(0);
            mContent = (ViewGroup) mWapper.getChildAt(1);

            mMenuWidth = mMenu.getLayoutParams().width = mScreenWidth - mMenuRightPadding;
            mContent.getLayoutParams().width = mScreenWidth;
            once = true;
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

定义偏移量,实现隐藏

    /**
     * 通过设置偏移量,讲menu隐藏
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        if (changed) {
            this.scrollTo(mMenuWidth, 0);
        }
    }

滑动事件

我们怎么来判定是否滑动了这个滚动条呢,并通过这个来显示不同的页面,这就是我们要解决的问题,在这里我们可以onTouchEvent方法来实现,因为只有当我们从屏幕上吧手指抬起来的时候才是我们需要的位置

@Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_UP:
                //隐藏在做左边的宽度
                int scrollX = getScrollX();

                if (scrollX >= mMenuWidth * 1.0f / 2) {
                    this.smoothScrollTo(mMenuWidth, 0);
                    isOpen = false;
                } else {
                    this.smoothScrollTo(0, 0);
                    isOpen = true;
                }
                return true;
        }

        return super.onTouchEvent(ev);
    }

activity.xml文件的处理

在这里我们用的是新建的xml,名称为left_menu.xml 逻辑也是很简单的

内部逻辑:

  • 用一个水平排列的LinearLayout
  • 在LinearLayout内部嵌套RelativeLayout(虽然这样嵌套可能会导致性能收到影响,但我们现在重在理解这个过程)
  • 在每个RelativeLayout中在添加ImageView和TextView

这样我们要实现的左边菜单栏,默认隐藏的菜单栏就写好了,代码如下,大家可以选择性的参考:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/id_img1"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_1"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/id_img1"
                android:text="第一个item"
                android:textColor="#b41dbc"
                android:textSize="20sp"/>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/id_img2"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_2"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/id_img2"
                android:text="第二个item"
                android:textColor="#b41dbc"
                android:textSize="20sp"/>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/id_img3"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_3"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/id_img3"
                android:text="第三个item"
                android:textColor="#b41dbc"
                android:textSize="20sp"/>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/id_img4"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_4"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/id_img4"
                android:text="第四个item"
                android:textColor="#b41dbc"
                android:textSize="20sp"/>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/id_img5"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_5"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/id_img5"
                android:text="第五个item"
                android:textColor="#b41dbc"
                android:textSize="20sp"/>
        </RelativeLayout>

    </LinearLayout>

</RelativeLayout>

其中str中引用的图片请自行准备。。。

打开菜单

    /**
     * 打开菜单
     */
    public void openMenu() {
        if (isOpen) return;
        this.smoothScrollTo(0, 0);
        isOpen = true;
    }

关闭菜单

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        if (!isOpen) return;
        this.smoothScrollTo(mMenuWidth, 0);
        isOpen = false;
    }

切换菜单

    /**
     * 切换菜单
     */
    public void toggle() {
        if (isOpen) {
            closeMenu();
        } else {
            openMenu();
        }
    }

在主页面中引用自定义view

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:qq_menu="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.earthchen.qq_menu.MainActivity">

    <com.earthchen.qq_menu.view.SlidingMenu
        android:id="@+id/id_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        qq_menu:rightPadding="100dp">
        
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <include layout="@layout/left_menu"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/main">
                
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="toggleMenu"
                    android:text="切换菜单"/>

            </LinearLayout>


        </LinearLayout>

    </com.earthchen.qq_menu.view.SlidingMenu>
</RelativeLayout>

在MainActivity中使用自定义控件

public class MainActivity extends AppCompatActivity {

    private SlidingMenu mLeftMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLeftMenu = (SlidingMenu) findViewById(R.id.id_menu);


    }

    public void toggleMenu(View view) {
        mLeftMenu.toggle();

    }
}

运行结果

以下即为最终运行的结果

qq_menu1

qq_menu2


注:

  • 上述代码在Android studio2.2中编译成功运行,其他ide请自行测试
  • 上述文字皆为个人看法,如有错误或建议请及时联系我
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,142评论 25 708
  • 最近,由于正在做的一个应用中要用到侧滑菜单,所以通过查资料看视频,学习了一下自定义View,实现一个类似于QQ的侧...
    冰鉴IT阅读 5,186评论 14 35
  • 人生路上 遇见是主题 或许幸事 或许不幸 何时何地 无从选择 人生路上 时而鲜花满地 时而荆棘丛生 没有退路 唯有...
    胡杨公主阅读 241评论 7 10
  • 在 viewDidAppear 关闭手势功能 在 viewWillDisAppear 打开手势功能 self.na...
    IRONYT阅读 311评论 0 0
  • 云海天涯两渺茫。何日功成名遂了,还乡,醉笑陪公三万场,不用诉离殇。 ...
    剁椒鱼头头阅读 226评论 0 0