欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android自定义View实现分段选择按钮的实现代码

程序员文章站 2022-07-08 18:09:51
首先演示下效果,分段选择按钮,支持点击和滑动切换。视图绘制过程中,要执行onmeasure、onlayout、ondraw等方法,这也是自定义控件最常用到的几个方法。onmeasure:测量视图的大小...

首先演示下效果,分段选择按钮,支持点击和滑动切换。

Android自定义View实现分段选择按钮的实现代码

视图绘制过程中,要执行onmeasureonlayoutondraw等方法,这也是自定义控件最常用到的几个方法。
onmeasure:测量视图的大小,可以根据measurespec的mode确定父视图和子视图的大小。
onlayout:确定视图的位置
ondraw:绘制视图
这里就不做过多的介绍,主要介绍本控件涉及的到的部分。

1.1 获取item大小、起始位置

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  super.onmeasure(widthmeasurespec, heightmeasurespec);

  if(isitemzero() || getmeasuredwidth() == 0)
   return;

  mheight = getmeasuredheight();
  int width = getmeasuredwidth();
  mitemwidth = (width - 2 * itemhorizontalmargin)/getcount();
  mstart = itemhorizontalmargin + mitemwidth * selecteditem;
  mend = width - itemhorizontalmargin - mitemwidth;
 }

1.2 绘制

绘制背景,所有的item,以及选中项

 @override
 protected void ondraw(canvas canvas) {
  super.ondraw(canvas);

  if(isitemzero())
   return;

  drawbackgroundrect(canvas);

  drawunselecteditemstext(canvas);

  drawselecteditem(canvas);

  drawselecteditemstext(canvas);
 }

* 绘制背景区域

背景区域就是个带圆角的长方形

 /**
  * 画背景区域
  * @param canvas
  */
 private void drawbackgroundrect(canvas canvas) {
  float r = cornersmode == round?cornersradius: mheight >> 1;
  mpaint.setxfermode(null);
  mpaint.setcolor(backgroundcolor);
  mrectf.set(0, 0, getwidth(), getheight());
  canvas.drawroundrect(mrectf, r, r, mpaint);
 }

* 绘制所有未选中item的文字

轮流绘制所有item的文字

 /**
  * 画所有未选中item的文字
  * @param canvas
  */
 private void drawunselecteditemstext(canvas canvas) {
  mtextpaint.setcolor(textcolor);
  mtextpaint.setxfermode(null);
  for (int i = 0; i< getcount(); i++){
   int start = itemhorizontalmargin + i * mitemwidth;
   float x = start + (mitemwidth >> 1) - mtextpaint.measuretext(getname(i))/2;
   float y = (getheight() >> 1) - (mtextpaint.ascent() + mtextpaint.descent())/2;
   canvas.drawtext(getname(i), x, y, mtextpaint);
  }
 }

* 绘制选中项

 /**
  * 画选中项
  * @param canvas
  */
 private void drawselecteditem(canvas canvas) {
  float r = cornersmode == round?cornersradius: (mheight >> 1) - itemverticalmargin;
  mpaint.setcolor(selecteditembackgroundcolor);
  mrectf.set(mstart, itemverticalmargin, mstart + mitemwidth, getheight() - itemverticalmargin);
  canvas.drawroundrect(mrectf, r, r, mpaint);
 }

* 绘制选中item的文字

当选中项移动时,刚移动到下一个item时,颜色应该是选中的颜色。这里在原来文字之上再画选中item的文字颜色,就有了被选中的效果。

 /**
  * 画选中item的文字
  * @param canvas
  */
 private void drawselecteditemstext(canvas canvas) {
  canvas.savelayer(mstart, 0, mstart + mitemwidth, getheight(), null, canvas.all_save_flag);
  mtextpaint.setcolor(selecteditemtextcolor);
  mtextpaint.setxfermode(new porterduffxfermode(porterduff.mode.src_out));
  int begin = mstart/mitemwidth;
  int end = (begin + 2) < getcount()?begin+2:getcount();

  for (int i = begin; i< end; i++){
   int start = itemhorizontalmargin + i * mitemwidth;
   float x = start + (mitemwidth >> 1) - mtextpaint.measuretext(getname(i))/2;
   float y = (getheight() >> 1) - (mtextpaint.ascent() + mtextpaint.descent())/2;
   canvas.drawtext(getname(i), x, y, mtextpaint);
  }
  canvas.restore();
 }

1.3 添加手势事件

手势分为三种,action_down、action_move、action_up,对应动作就是按下,滑动,按起。
当按下时确定按下位置,是在当前item,则不做处理,当按下位置为其它item位置,就滑动到其它item位置。
当手势滑动时,计算相对滑动值,通过改变mstart,改变选中项的位置。
当手势按起时,根据按下位置、速度和方向,判断是否可用移动到下一个item。

 @override
 public boolean ontouchevent(motionevent event) {

  if(!isenabled() || !isintouchmode() || getcount() == 0)
   return false;

  if (mvelocitytracker == null) {
   mvelocitytracker = velocitytracker.obtain();
  }
  mvelocitytracker.addmovement(event);

  int action = event.getactionmasked();
  if(action == motionevent.action_down){
   x = event.getx();
   onclickdownposition = -1;
   final float y = event.gety();
   if(isiteminside(x, y)){
    return scrollselectenabled;
   }else if(isitemoutside(x, y)){
    if(!mscroller.isfinished()){
     mscroller.abortanimation();
    }
    onclickdownposition = (int) ((x - itemhorizontalmargin)/ mitemwidth);
    startscroll(positionstart(x));
    return true;
   }
   return false;
  }else if(action == motionevent.action_move){
   if(!mscroller.isfinished() || !scrollselectenabled){
    return true;
   }
   float dx = event.getx() - x;
   if(math.abs(dx) > min_move_x){
    mstart = (int) (mstart + dx);
    mstart = math.min(math.max(mstart, itemhorizontalmargin), mend);
    postinvalidate();
    x = event.getx();
   }
   return true;
  }else if(action == motionevent.action_up){

   int newselecteditem;
   float offset = (mstart - itemhorizontalmargin)%mitemwidth;
   float itemstartposition = (mstart - itemhorizontalmargin) * 1.0f/ mitemwidth;

   if(!mscroller.isfinished() && onclickdownposition != -1){
    newselecteditem = onclickdownposition;
   }else{
    if(offset == 0f){
     newselecteditem = (int)itemstartposition;
    }else {
     velocitytracker velocitytracker = mvelocitytracker;
     velocitytracker.computecurrentvelocity(velocity_units, mmaximumflingvelocity);
     int initialvelocity = (int) velocitytracker.getxvelocity();

     float itemrate = offset/mitemwidth;
     if (isxvelocitycanmovenextitem(initialvelocity, itemrate)){
      newselecteditem = initialvelocity > 0?(int)itemstartposition+1:(int)itemstartposition;
     }else {
      newselecteditem = math.round(itemstartposition);
     }
     newselecteditem = math.max(math.min(newselecteditem, getcount() - 1), 0);
     startscroll(getxbyposition(newselecteditem));
    }
   }
   onstatechange(newselecteditem);
   mvelocitytracker = null;
   onclickdownposition = -1;
   return true;
  }
  return super.ontouchevent(event);
 }

1.4 保存状态

当手机屏幕方向转换或者内存不足等情况下, 视图会重新加载,这样就会导致状态丢失。使用onsaveinstancestateonrestoreinstancestate方法保存并恢复状态。

 @override
 public parcelable onsaveinstancestate() {
  parcelable parcelable = super.onsaveinstancestate();
  selecteditemstate pulltoloadstate = new selecteditemstate(parcelable);
  pulltoloadstate.setselecteditem(selecteditem);
  return pulltoloadstate;
 }

 @override
 public void onrestoreinstancestate(parcelable state) {
  if(!(state instanceof selecteditemstate))
   return;
  selecteditemstate pulltoloadstate = ((selecteditemstate)state);
  super.onrestoreinstancestate(pulltoloadstate.getsuperstate());
  selecteditem = pulltoloadstate.getselecteditem();
  invalidate();
 }

想要学习的同学,建议还是直接看项目源码。项目源码地址:https://github.com/danledian/segmentedcontrol

到此这篇关于android自定义view实现分段选择按钮的文章就介绍到这了,更多相关android自定义view分段选择按钮内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!