本文已授权微信公众号:鸿洋(hongyangAndroid)原创首发。
我的开源库:一句代码搞定 RecycleView 侧滑菜单、添加头部底部、加载更多
在实现 Recycleview 侧滑菜单时起初使用了开源库 SwipeRecyclerView ,此库功能广泛,但无法满足个人需求,这是因为此库中存在以下局限性:
- 菜单文字一旦确定将无法修改
- 侧滑时整个 item 都会滑动
- 无法自定义菜单样式
只能自己实现了,查阅资料后发现,较多通过 DragHelper 实现的,它是一个手势滑动辅助工具,使 item 可以滑动,然后… , 等等!既然目的是让 item 可以滑动,那为什么不直接在 item 布局中使用 HorizontalScrollView 呢?参考鸿神的Android 自定义控件打造史上最简单的侧滑菜单,标题致敬一波~
首先是自定义 SlidingMenu :
public class SlidingMenu extends HorizontalScrollView {
private static final float radio = 0.3f;//菜单占屏幕宽度比
private final int mScreenWidth;
private final int mMenuWidth;
private boolean once = true;
public SlidingMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mScreenWidth = ScreenUtil.getScreenWidth(context);
mMenuWidth = (int) (mScreenWidth * radio);
setOverScrollMode(View.OVER_SCROLL_NEVER);
setHorizontalScrollBarEnabled(false);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (once) {
LinearLayout wrapper = (LinearLayout) getChildAt(0);
wrapper.getChildAt(0).getLayoutParams().width = mScreenWidth;
wrapper.getChildAt(1).getLayoutParams().width = mMenuWidth;
once = false;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
case MotionEvent.ACTION_UP:
int scrollX = getScrollX();
if (Math.abs(scrollX) > mMenuWidth / 2) {
this.smoothScrollTo(mMenuWidth, 0);
} else {
this.smoothScrollTo(0, 0);
}
return true;
}
return super.onTouchEvent(ev);
}
}
在 item 布局中应用 SlidingMenu,注意 SlidingMenu 中是按照顺序区分 content 和 menu 的,所以布局文件中顺序要对应一致 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:orientation="vertical"
>
<com.xmwj.slidingmenu.SlidingMenu
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<LinearLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#af6fe1"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="置顶"
android:textColor="#fff"
android:gravity="center"
android:background="@color/colorAccent"
/>
</LinearLayout>
</LinearLayout>
</com.xmwj.slidingmenu.SlidingMenu>
</LinearLayout>