自定义ListView 侧滑菜单
版权声明:本文为博主原创文章,未经博主允许不得转载。
作为一名中级程序猿实在忍受不了,每个项目都是用着别人的开源控件
所以决定在2016年的上半年一定要成为高级工程师,
然而成为高级程序猿以下下7条是绝对要会,的不会一条都不能叫高级程序猿:
- AIDL:熟悉AIDL,理解其工作原理,懂transact和onTransact的区别;
- Binder:从Java层大概理解Binder的工作原理,懂Parcel对象的使用;
- 多进程:熟练掌握多进程的运行机制,懂Messenger、Socket等;
- 事件分发:弹性滑动、滑动冲突等;
- 玩转View:View的绘制原理、各种自定义View;
- 动画系列:熟悉View动画和属性动画的不同点,懂属性动画的工作原理;
- 懂性能优化、熟悉mat等工具
- 懂点常见的设计模式学习方法
为了让自己尽快成为高级程序猿,我觉得一定要写点自己博客以及常用的控件
如果你也想一样不想一辈子混日子那就动起来,其中学习过程我是参考
CSDN中任玉刚的博客 链接:http://blog.csdn.net/singwhatiwanna/article/details/49560409
推荐的书我也买啦,总之受益不浅,废话就不说上代码:
SwipeMenuView :
自定义 LineLayout 侧滑菜单按钮,这个类比较简单就不打算说废话
通过new SwipeMenuView 传入一个对象对象中包含一个List 、
把List迭代添加TextView 或ImageView 到此结束
/**
* @author Liqingqingqingwe!
* @data 2015/12/18
*/
public class SwipeMenuView extends LinearLayout implements OnClickListener{
private Context mContext;
private LayoutParams mLayoutParams;
private SwipeMenu menu;
private SwipeMenuListView menuListView;
private SwipeMenuItemClickListener menuItemClickListener;
private int position;
public SwipeMenuView(Context context) {
super(context);
}
public SwipeMenuView(Context context,AttributeSet attr) {
super(context,attr);
}
public SwipeMenuView(Context context,AttributeSet attr,int defStyleAttr) {
super(context,attr,defStyleAttr);
}
public SwipeMenuView(SwipeMenu menu ,SwipeMenuListView menuListView ) {
super(menu.getmContext());
this.mContext = menu.getmContext();
this.menu = menu;
this.menuListView = menuListView;
int id = 0;
for (SwipeMenuItem item : menu.getmItems()) {
addView(item,++id);
}
}
private void addView(SwipeMenuItem item,int id) {
mLayoutParams = new LayoutParams(item.getWidth(),LayoutParams.MATCH_PARENT);
setId(id);
// setBackgroundResource(item.getBackgRound());
// setGravity(Gravity.CENTER_VERTICAL);
setOrientation(LinearLayout.HORIZONTAL);
if(item.getIcon() != 0)
addView(addImageView(item));
else if(!TextUtils.isEmpty(item.getText()))
addView(addTextView(item));
}
private TextView addTextView(SwipeMenuItem item) {
TextView mTextView = new TextView(mContext);
mTextView.setLayoutParams(mLayoutParams);
mTextView.setText(item.getText());
mTextView.setGravity(Gravity.CENTER);
mTextView.setTextColor(item.getTextColor());
mTextView.setTextSize(item.getTextSize());
mTextView.setBackgroundResource(item.getBackgRound());
mTextView.setOnClickListener(this);
return mTextView;
}
private ImageView addImageView(SwipeMenuItem item) {
ImageView mImageView = new ImageView(mContext);
mImageView.setLayoutParams(mLayoutParams);
mImageView.setScaleType(ScaleType.CENTER);
mImageView.setImageResource(item.getIcon());
mImageView.setBackgroundResource(item.getBackgRound());
mImageView.setOnClickListener(this);
return mImageView;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
@Override
public void onClick(View v) {
if(menuItemClickListener != null){
menuItemClickListener.onSwipeItemClick(v, menu, position);
}
}
public SwipeMenuItemClickListener getMenuItemClickListener() {
return menuItemClickListener;
}
public void setMenuItemClickListener(
SwipeMenuItemClickListener menuItemClickListener) {
this.menuItemClickListener = menuItemClickListener;
}
public interface SwipeMenuItemClickListener{
public void onSwipeItemClick(View v,SwipeMenu menu , int position);
}
}
SwipeMenuItem :
实体类
/**
* @author Liqingqingqingwe!
* @data 2015/12/18
*/
public class SwipeMenuItem{
private int id;
private int backgRound;
private int textColor;
private int textSize;
private String text;
private int icon;
private int width;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBackgRound() {
return backgRound;
}
public void setBackgRound(int backgRound) {
this.backgRound = backgRound;
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public int getTextSize() {
return textSize;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
SwipeMenu:
包含的List<SwipeMenuItem >实体类
/**
* @author Liqingqingqingwe!
* @data 2015/12/18
*/
public class SwipeMenu {
private Context mContext;
private List<SwipeMenuItem> mItems = new ArrayList<SwipeMenuItem>();
private int type;
public SwipeMenu(Context mContext) {
this.mContext = mContext;
}
public void addMenuItem(SwipeMenuItem item) {
mItems.add(item);
}
public void removeMenuItem(SwipeMenuItem item) {
mItems.remove(item);
}
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public List<SwipeMenuItem> getmItems() {
return mItems;
}
public void setmItems(List<SwipeMenuItem> mItems) {
this.mItems = mItems;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
SwipeMenuLayout :
该自定义SwipeMenuLayout 布局通过 SwipeMenuListViewAdapter 拿到 ListView 的 ItemView , “ SwipeMenuListViewAdapter实现android.widget.WrapperListAdapter接口,该接口封装了另一个列表适配器的列表适配器。调用 getWrappedAdapter()可以取得封装在其中的适配器。具体请自行查API
这里只考虑怎么实现 ”
SwipeMenuLayout 布局通过SwipeMenuListView传递OnTouchMotionEvent事件来判断当前滑动偏移值,当滑动到SwipeMenuView宽度的一半则使用ScrollerCompat来进行动画“ 其实也可以使用属性动画来做 ” 由于这个类也不复杂这里只说思想而没有在代码中加注释。
/**
* @author Liqingqingqingwe!
* @data 2015/12/18
*/
public class SwipeMenuLayout extends FrameLayout {
private static final int CONVERT_VIEW_ID = 1;
private static final int SWIPEMENU_VIEW_ID = 2;
private static final int STATE_CLOSE = 1;
private static final int STATE_OPEN = 2;
private int state = STATE_CLOSE;
private int MIN_FLING = dp2px(10);
private int MAX_VELOCITYX = -dp2px(300);
private int mDownX;
private int mBaseX;
private SwipeMenu menu;
private SwipeMenuListView menuListView;
private SwipeMenuView menuView;
private View contentView;
private int position;
private Interpolator closeInterpolator;
private Interpolator openInterpolator;
private ScrollerCompat closeScrollerCompat;
private ScrollerCompat openScrollerCompat;
private OnGestureListener mOnGestureListener;
private GestureDetectorCompat mGestureDetectorCompat;
private boolean isFling;
public SwipeMenuLayout(Context context) {
super(context);
}
public SwipeMenuLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeMenuLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SwipeMenuLayout(SwipeMenu menu,SwipeMenuView menuView,SwipeMenuListView menuListView,View contentView,Interpolator closeInterpolator,Interpolator openInterpolator) {
super(menu.getmContext());
this.menu = menu;
this.menuListView = menuListView;
this.menuView = menuView;
this.contentView = contentView;
this.closeInterpolator = closeInterpolator;
this.openInterpolator = openInterpolator;
init();
}
private void init() {
setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
mOnGestureListener = new SimpleOnGestureListener(){
@Override
public boolean onDown(MotionEvent e) {
isFling = false;
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,float velocityX, float velocityY) {
if ((e1.getX() - e2.getX()) > MIN_FLING && velocityX < MAX_VELOCITYX) {
isFling = true;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
};
mGestureDetectorCompat = new GestureDetectorCompat(menu.getmContext(), mOnGestureListener);
if(closeInterpolator != null){
closeScrollerCompat =ScrollerCompat.create(getContext(), closeInterpolator);
}else{
closeScrollerCompat =ScrollerCompat.create(getContext());
}
if(openInterpolator != null){
openScrollerCompat =ScrollerCompat.create(getContext(), openInterpolator);
}else{
openScrollerCompat =ScrollerCompat.create(getContext());
}
contentView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
if(contentView.getId() > CONVERT_VIEW_ID){
contentView.setId(CONVERT_VIEW_ID);
}
menuView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
menuView.setId(SWIPEMENU_VIEW_ID);
addView(contentView);
addView(menuView);
}
public boolean onSwipeTouch(MotionEvent ev){
mGestureDetectorCompat.onTouchEvent(ev);
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = (int)ev.getX();
isFling = false;
break;
case MotionEvent.ACTION_MOVE:
int dis = (int) (mDownX - ev.getX() );
if(state == STATE_OPEN){
dis += menuView.getWidth();
}
onSwipe(dis);
break;
case MotionEvent.ACTION_UP:
if(isFling || (mDownX - ev.getX()) > (menuView.getWidth() / 2)){
smoothOpen();
}else{
smoothClose();
return false;
}
break;
default:
break;
}
return true;
}
public void smoothOpen(){
state = STATE_OPEN;
openScrollerCompat.startScroll(-contentView.getLeft(), 0, menuView.getWidth(),0, 350);
postInvalidate();
}
public void smoothClose(){
state = STATE_CLOSE;
mBaseX = -contentView.getLeft();
closeScrollerCompat.startScroll(0, 0, mBaseX,0, 350);
postInvalidate();
}
public void closeMenu(){
if(closeScrollerCompat.computeScrollOffset()){
closeScrollerCompat.abortAnimation();
}
if (state == STATE_OPEN) {
state = STATE_CLOSE;
onSwipe(0);
}
}
public void openMenu(){
if (state ==STATE_CLOSE ) {
state = STATE_OPEN;
onSwipe(menuView.getWidth());
}
}
public void onSwipe(int dis){
if(dis >= menuView.getWidth()){
dis = menuView.getWidth();
}
if(dis < 0){
dis = 0;
}
contentView.layout(-dis, contentView.getTop(), contentView.getWidth() - dis, getMeasuredHeight());
menuView.layout(contentView.getWidth() - dis, menuView.getTop(), (contentView.getWidth() + menuView.getWidth()) - dis , menuView.getBottom());
}
@Override
public void computeScroll() {
super.computeScroll();
if(state == STATE_OPEN){
if(openScrollerCompat.computeScrollOffset()){
onSwipe(openScrollerCompat .getCurrX());
postInvalidate();
}
}else{
if(closeScrollerCompat.computeScrollOffset()){
onSwipe(mBaseX - closeScrollerCompat.getCurrX());
postInvalidate();
}
}
}
public boolean isOpen(){
return state == STATE_OPEN;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
contentView.layout(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight());
menuView.layout(contentView.getMeasuredWidth(), 0, menuView.getMeasuredWidth() +contentView.getMeasuredWidth() , contentView.getMeasuredHeight());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
menuView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
menuView.setPosition(position);
}
private int dp2px(int dp){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
}
}
SwipeMenuListViewAdapter :
SwipeMenuListViewAdapter实现 WrapperListAdapter接口前面大概说了一下,其实这个接口重点代码在getView的方法上,其他方法通过传进来的ListAdapter来解决就可以啦简单粗暴具体看代码,而getView方法做了什么:
仔细看起来和我们平常写的Adapter没多大区别 其实现方式就是把我们的ListView中的Item获到传入到SwipeMenuLayout 布局中进行封装包一层。重点在getView方法中!
/**
* @author Liqingqingqingwe!
* @data 2015/12/18
*/
public class SwipeMenuListViewAdapter implements WrapperListAdapter,SwipeMenuItemClickListener{
private Context mContext;
private ListAdapter mAdapter;
public SwipeMenuListViewAdapter(Context mContext, ListAdapter mAdapter) {
this.mContext = mContext;
this.mAdapter = mAdapter;
}
@Override
public boolean areAllItemsEnabled() {
return mAdapter.areAllItemsEnabled();
}
@Override
public boolean isEnabled(int position) {
return mAdapter.isEnabled(position);
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
mAdapter.registerDataSetObserver(observer);
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
mAdapter.unregisterDataSetObserver(observer);
}
@Override
public int getCount() {
return mAdapter.getCount();
}
@Override
public Object getItem(int position) {
return mAdapter.getItem(position);
}
@Override
public long getItemId(int position) {
return mAdapter.getItemId(position);
}
@Override
public boolean hasStableIds() {
return mAdapter.hasStableIds();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
SwipeMenuLayout mSwipeMenuLayout= null;
if(convertView == null){
View contentView = mAdapter.getView(position, convertView, parent);
SwipeMenu menu = new SwipeMenu(mContext);
addMenu(menu);
SwipeMenuListView menuListView = (SwipeMenuListView) parent;
SwipeMenuView mSwipeMenuView = new SwipeMenuView(menu, menuListView);
mSwipeMenuView.setMenuItemClickListener(this);
mSwipeMenuLayout = new SwipeMenuLayout(menu, mSwipeMenuView, menuListView, contentView, menuListView.getmCloseInterpolator(), menuListView.getmOpenInterpolator());
mSwipeMenuLayout.setPosition(position);
}else{
mSwipeMenuLayout = (SwipeMenuLayout) convertView;
mSwipeMenuLayout.setPosition(position);
mSwipeMenuLayout.closeMenu();
}
return mSwipeMenuLayout;
}
public void addMenu(SwipeMenu menu) {
}
@Override
public int getItemViewType(int position) {
return mAdapter.getItemViewType(position);
}
@Override
public int getViewTypeCount() {
return mAdapter.getViewTypeCount();
}
@Override
public boolean isEmpty() {
return mAdapter.isEmpty();
}
@Override
public ListAdapter getWrappedAdapter() {
return mAdapter;
}
@Override
public void onSwipeItemClick(View v, SwipeMenu menu, int position) {
}
SwipeMenuListView :
最后最重要的一个类ListView, 重点onTouchEvent事件中 有注释看注释就明白啦。
private static final int TOUCH_STATE_NONE = 0;
private static final int TOUCH_STATE_X = 1;
private static final int TOUCH_STATE_Y = 2;
private int MAX_Y = 5;
private int MAX_X = 3;
private SwipeMenuItemClickListener menuItemClickListener;
private SwipeAddMenuListener mAddMenuListener;
private Interpolator mCloseInterpolator;
private Interpolator mOpenInterpolator;
private SwipeMenuLayout menuLayout;
private int mDwonX;
private int mDwonY;
private int mTouchState;
private int mTouchPosition;
public SwipeMenuListView(Context context) {
super(context);
init();
}
public SwipeMenuListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SwipeMenuListView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
MAX_X = dp2px(MAX_X);
MAX_Y = dp2px(MAX_Y);
mTouchState = TOUCH_STATE_NONE;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(ev.getAction() != MotionEvent.ACTION_DOWN && menuLayout == null )
return super.onTouchEvent(ev);
int action = MotionEventCompat.getActionMasked(ev);
switch (action) {
case MotionEvent.ACTION_DOWN:
int oldPos = mTouchPosition;
mDwonX = (int)ev.getX();
mDwonY = (int)ev.getY();
mTouchState = TOUCH_STATE_NONE;
// 根据坐标调用pointToPosition(x,y)方法算出触摸的Item
mTouchPosition = pointToPosition((int)ev.getX(), (int)ev.getY());
if(oldPos == mTouchPosition && menuLayout != null && menuLayout.isOpen()){
mTouchState = TOUCH_STATE_X;
menuLayout.onSwipeTouch(ev);
return true;
}
//第二次点击 如果 menuLayout 不为空 并且是侧滑是打开的那么就关闭侧滑菜单
if(menuLayout != null && menuLayout.isOpen() ){
menuLayout.smoothClose();
menuLayout = null;
return super.onTouchEvent(ev);
}
// 拿到触摸的Item 判断是否为侧滑菜单
View v = getChildAt(mTouchPosition - getFirstVisiblePosition());
if(v instanceof SwipeMenuLayout){
menuLayout = (SwipeMenuLayout) v;
}
if(menuLayout != null){
menuLayout.onSwipeTouch(ev);
}
break;
case MotionEvent.ACTION_MOVE:
float dx = Math.abs((mDwonX - ev.getX()));
float dy = Math.abs((mDwonY - ev.getY()));
if(mTouchState == TOUCH_STATE_X){
if(menuLayout != null){
menuLayout.onSwipeTouch(ev);
}
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
}else if(mTouchState == TOUCH_STATE_NONE){
if(dx > MAX_X){
mTouchState = TOUCH_STATE_X;
}else if(dy > MAX_Y){
mTouchState = TOUCH_STATE_Y;
}
}
break;
case MotionEvent.ACTION_UP:
// 放开触摸 如果当前侧滑菜单是打开的直接拦截Touch事情不做任何处理否则清空View
if(mTouchState == TOUCH_STATE_X){
menuLayout.onSwipeTouch(ev);
if(menuLayout != null){
if (!menuLayout.isOpen()) {
mTouchPosition = -1;
menuLayout = null;
}
}
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
}
break;
default:
break;
}
return super.onTouchEvent(ev);
}
public void openMenu(int poition){
if(poition >= getFirstVisiblePosition() && poition<= getLastVisiblePosition()){
View v = getChildAt(poition - getFirstVisiblePosition());
if(v instanceof SwipeMenuLayout){
if(menuLayout != null && menuLayout.isOpen() ){
menuLayout.smoothClose();
menuLayout = null;
}
menuLayout = (SwipeMenuLayout) v;
menuLayout.smoothOpen();
}
}
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(new SwipeMenuListViewAdapter(getContext(), adapter){
@Override
public void addMenu(SwipeMenu menu) {
super.addMenu(menu);
if(mAddMenuListener != null){
mAddMenuListener.addMenu(menu);
}
}
@Override
public void onSwipeItemClick(View v, SwipeMenu menu, int position) {
super.onSwipeItemClick(v, menu, position);
if(menuItemClickListener != null){
if(menuLayout.isOpen()){
menuLayout.smoothClose();
}
menuItemClickListener.onSwipeItemClick(v, menu, position);
}
}
});
}
public Interpolator getmCloseInterpolator() {
return mCloseInterpolator;
}
public void setmCloseInterpolator(Interpolator mCloseInterpolator) {
this.mCloseInterpolator = mCloseInterpolator;
}
public Interpolator getmOpenInterpolator() {
return mOpenInterpolator;
}
public void setmOpenInterpolator(Interpolator mOpenInterpolator) {
this.mOpenInterpolator = mOpenInterpolator;
}
public SwipeMenuItemClickListener getMenuItemClickListener() {
return menuItemClickListener;
}
public void setMenuItemClickListener(
SwipeMenuItemClickListener menuItemClickListener) {
this.menuItemClickListener = menuItemClickListener;
}
public SwipeAddMenuListener getmAddMenuListener() {
return mAddMenuListener;
}
public void setmAddMenuListener(SwipeAddMenuListener mAddMenuListener) {
this.mAddMenuListener = mAddMenuListener;
}
public interface SwipeMenuItemClickListener{
public void onSwipeItemClick(View v,SwipeMenu menu , int position);
}
public interface SwipeAddMenuListener{
public void addMenu(SwipeMenu menu);
}
private int dp2px(int dp){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
}
运行效果图:
Screenshot_2015-12-22-16-43-38.png
该控件参考 https://github.com/baoyongzhang/SwipeMenuListView
做一些改进后期考虑加入更多使用场景
没有提供下载链接 如果有需要Sample请回复留邮箱~
最后说一句:由于本人是第一次写博客,写的不清不楚的地方请尽情的侮辱我吧~
金馆长.gif