这里做的是一个侧滑菜单~~
1、原理分析
需要滑动可以出现另一个,既然这样,大家为啥不考虑使用Android提供的HorizontalScrollView呢~
如果使用HorizontalScrollView,还需要在ACTION_DOWN , ACTION_MOVE里面去监听,判断,不断改变控件位置了么? NO!!!HorizontalScrollView本身就带了滑动的功能~~
还需要自己的手动处理各种冲突么?NO!!!当然了,还是需要了解下事件分发机制的~~~
2、效果图
3.源码
<com.example.zhy_slidingmenu.SlidingMenu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<include layout="@layout/layout_menu" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/qq" >
</LinearLayout>
</LinearLayout>
</com.example.zhy_slidingmenu.SlidingMenu>
4、自定义SlidingMenu
package com.example.zhy_slidingmenu;
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import com.zhy.utils.ScreenUtils;
public class SlidingMenu extends HorizontalScrollView
{
/**
* 屏幕宽度
*/
private int mScreenWidth;
/**
* dp
*/
private int mMenuRightPadding = 50;
/**
* 菜单的宽度
*/
private int mMenuWidth;
private int mHalfMenuWidth;
private boolean once;
public SlidingMenu(Context context, AttributeSet attrs)
{
super(context, attrs);
mScreenWidth = ScreenUtils.getScreenWidth(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
/**
* 显示的设置一个宽度
*/
if (!once)
{
LinearLayout wrapper = (LinearLayout) getChildAt(0);
ViewGroup menu = (ViewGroup) wrapper.getChildAt(0);
ViewGroup content = (ViewGroup) wrapper.getChildAt(1);
// dp to px
mMenuRightPadding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, mMenuRightPadding, content
.getResources().getDisplayMetrics());
mMenuWidth = mScreenWidth - mMenuRightPadding;
mHalfMenuWidth = mMenuWidth / 2;
menu.getLayoutParams().width = mMenuWidth;
content.getLayoutParams().width = mScreenWidth;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@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);
once = true;
}
}
@Override
public boolean onTouchEvent(MotionEvent ev)
{
int action = ev.getAction();
switch (action)
{
// Up时,进行判断,如果显示区域大于菜单宽度一半则完全显示,否则隐藏
case MotionEvent.ACTION_UP:
int scrollX = getScrollX();
if (scrollX > mHalfMenuWidth)
this.smoothScrollTo(mMenuWidth, 0);
else
this.smoothScrollTo(0, 0);
return true;
}
return super.onTouchEvent(ev);
}
}
3、添加ListView测试
这样就结束啦~~~