当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 自定义组件卫星菜单的实现

Android 自定义组件卫星菜单的实现

2019年07月24日  | 移动技术网移动技术  | 我要评论
卫星菜单 arcmenu 相信大家接触安卓,从新手到入门的过渡,就应该会了解到卫星菜单、抽屉、xutils、coolmenu、一些大神封装好的一些组件。这些组件在

卫星菜单 arcmenu

相信大家接触安卓,从新手到入门的过渡,就应该会了解到卫星菜单、抽屉、xutils、coolmenu、一些大神封装好的一些组件。这些组件在 github 上面很容易搜得到,但是有时候打开会发现看不懂里面的代码,包括一些方法和函数 。。。。。
首先先上效果图:

实现效果

首先如果要想自定义组件

1.那么第一件事就是赋予自定义组件的属性,从效果图上看出,该组件可以存在屏幕的各个角落点,那么位置是其属性之一。

2.既然是卫星菜单,那么主按钮和其附属的小按钮之间的围绕半径也应该作为其参数之一。

3.右图得出,该组件包含很多按钮,主按钮和附属按钮,那么这个组件应该继承 viewgroup。

一、定义卫星菜单的属性在 values 包下建立 attr 的 xml 文件,赋予组件位置属性,和半径属性。

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <!-- 位置属性-->
  <attr name="position">
    <enum name="left_top" value="0" />
    <enum name="left_bottom" value="1" />
    <enum name="right_top" value="2" />
    <enum name="right_bottom" value="3" />
  </attr>

  <!-- 尺寸属性dp如果使用px可能会造成屏幕适配问题-->
  <attr name="radius" format="dimension" />
  <!-- 自定义属性-->
  <declare-styleable name="arcmenu">

    <attr name="position" />
    <attr name="radius" />


  </declare-styleable>


</resources>

二、编写自定义组件

package com.lanou.dllo.arcmenudemo.arcmenu;

import android.content.context;
import android.content.res.typedarray;
import android.util.attributeset;
import android.util.log;
import android.util.typedvalue;
import android.view.view;
import android.view.viewgroup;
import android.view.animation.alphaanimation;
import android.view.animation.animation;
import android.view.animation.animationset;
import android.view.animation.rotateanimation;
import android.view.animation.scaleanimation;
import android.view.animation.translateanimation;

import com.lanou.dllo.arcmenudemo.r;

/**
 * created by dllo on 16/3/25.
 * 1.首先arcmenu是继承viewgroup,那么一个卫星菜单包括一个大按钮和其他的子按钮群.
 */

public class arcmenu extends viewgroup implements view.onclicklistener {

  //设置常量,标识成枚举
  private static final int pos_left_top = 0;
  private static final int pos_left_bottom = 1;
  private static final int pos_right_top = 2;
  private static final int pos_right_bottom = 3;

  //以下5个成员变量是所需要的.
  //声明两个属性 位置 还有半径
  private position mposition = position.right_bottom;
  private int mradius;

  /**
   * 菜单的状态
   */
  private status mcurrentstatus = status.close;

  /**
   * 菜单的主按钮
   */
  private view mcbutton;

  //子菜单的回调按钮
  private onmenuitemclicklistener mmenuitemclicklistener;


  /**
   * 菜单的位置枚举类,4个位置
   */
  public enum position {
    left_top, left_bottom, right_top, right_bottom
  }

  public enum status {
    open, close
  }

  /**
   * 点击子菜单项,顺便把位置传递过去
   */
  public interface onmenuitemclicklistener {
    void onclick(view view, int pos);
  }

  //3个构造方法,相互传递.
  //注意别写错误.
  public arcmenu(context context) {
    this(context, null);
  }

  public arcmenu(context context, attributeset attrs) {
    this(context, attrs, 0);
  }

  public arcmenu(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);
    //typedvalue.applydimension是转变标准尺寸的方法 参数一:单位  参数二:默认值 参数三:可以获取当前屏幕的分辨率信息.
    mradius = (int) typedvalue.applydimension(typedvalue.complex_unit_dip
        , 100, getresources().getdisplaymetrics());

    //获取自定义属性的值
    //参数1:attrs attributeset是节点的属性集合
    //参数2:attrs的一个数组集
    //参数3:指向当前theme 某个item 描述的style 该style指定了一些默认值为这个typedarray
    //参数4;当defstyleattr 找不到或者为0, 可以直接指定某个style
    typedarray a = context.gettheme().obtainstyledattributes(attrs,
        r.styleable.arcmenu, defstyleattr, 0);
    int pos = a.getint(r.styleable.arcmenu_position, pos_right_bottom);
    switch (pos) {
      case pos_left_top:
        mposition = position.left_top;
        break;
      case pos_left_bottom:
        mposition = position.left_bottom;
        break;
      case pos_right_top:
        mposition = position.right_top;
        break;
      case pos_right_bottom:
        mposition = position.right_bottom;
        break;
    }

    mradius = (int) a.getdimension(r.styleable.arcmenu_radius,
        typedvalue.applydimension(typedvalue.complex_unit_dip
            , 100, getresources().getdisplaymetrics()));

    log.d("tag", "position = " + mposition + ", radius" + mradius);
    //使用完必须回收.
    a.recycle();

  }

  public void setonmenuitemclicklistener(onmenuitemclicklistener mmenuitemclicklistener) {
    this.mmenuitemclicklistener = mmenuitemclicklistener;
  }

  /**
   * 测量方法
   */
  @override
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    int count = getchildcount();
    for (int i = 0; i < count; i++) {
      //测量child的各个属性.
      measurechild(getchildat(i), widthmeasurespec, heightmeasurespec);
    }
    super.onmeasure(widthmeasurespec, heightmeasurespec);
  }

  @override
  protected void onlayout(boolean changed, int l, int t, int r, int b) {
    if (changed) {
      layoutcbutton();
      //获得容器内组件的个数,并且包括这个主的组件(大按钮)
      int count = getchildcount();
      for (int i = 0; i < count - 1; i++) {
        //这里直接获取第一个,是因为getchildat(0)是红色的按钮.
        view child = getchildat(i + 1);
        //正常来说,如果设置按钮动画,移动出去后,是不能点击的,这里给按钮设置一个隐藏的属性.等卫星菜单飞过去,在让它们显示出来.
        child.setvisibility(view.gone);
        /**
         * 根据画图分析,得出每个子卫星按钮的夹角 a = 90°/(菜单的个数-1)
         * 假设menu总数为4,那么从左侧数menu1的坐标为(0,r);
         * menu2的坐标为(r*sin(a),r*cos(a));
         * menu3的坐标为(r*sin(2a),r*cos(2a));
         * ...
         * menun的坐标为(r,0);
         * 另:pi为π
         * */
        //测量每个子卫星组件的在屏幕上面的坐标距离
        //这里count-2,是因为count包含了主按钮
        //每个组件的坐标为(cl,ct);
        int cl = (int) (mradius * math.sin(math.pi / 2 / (count - 2) * i));
        int ct = (int) (mradius * math.cos(math.pi / 2 / (count - 2) * i));

        int cwidth = child.getmeasuredwidth();
        int cheight = child.getmeasuredheight();

        //如果卫星菜单存在于底部,那么坐标位置的计算方法,就完全相反.
        /**
         * 如果菜单位置在底部 左下 ,右下.坐标会发生变化
         * */
        if (mposition == position.left_bottom || mposition == position.right_bottom) {
          ct = getmeasuredheight() - cheight - ct;
        }

        /**
         * 右上,右下
         * */
        if (mposition == position.right_top || mposition == position.right_bottom) {
          cl = getmeasuredwidth() - cwidth - cl;
        }


        //子布局的测量坐标;
        child.layout(cl, ct, cl + cwidth, ct + cheight);


      }
    }

  }

  /**
   * 定位主菜单按钮
   */
  private void layoutcbutton() {
    // 给主按钮设置监听
    mcbutton = getchildat(0);
    mcbutton.setonclicklistener(this);

    //分别代表控件所处离左侧和上侧得距离
    int l = 0;
    int t = 0;
    int width = mcbutton.getmeasuredwidth();
    int height = mcbutton.getmeasuredheight();

    /**
     * getmeasuredheight()如果前面没有对象调用,那么这个控件继承viewgroup,就意味着这是获取容器的总高度.
     * getmeasuredwidth()也是同理.
     * 那么就可以判断出控件在四个位置(根据坐标系判断.)
     * */
    switch (mposition) {
      case left_top:
        l = 0;
        t = 0;
        break;
      case left_bottom:
        l = 0;
        t = getmeasuredheight() - height;
        break;
      case right_top:
        l = getmeasuredwidth() - width;
        t = 0;
        break;
      case right_bottom:
        l = getmeasuredwidth() - width;
        t = getmeasuredheight() - height;
        break;
    }

    //layout的四个属性.分别代表主按钮在不同位置距离屏幕左侧和上侧
    mcbutton.layout(l, t, l + width, t + height);

  }


  @override
  public void onclick(view v) {
    //主要确定mcbutton的值
    mcbutton = findviewbyid(r.id.id_button);
    if (mcbutton == null) {
      mcbutton = getchildat(0);
    }

    //旋转动画
    rotatecbutton(v, 0f, 360f, 300);
    //判断菜单是否关闭,如果菜单关闭需要给菜单展开,如果菜单是展开的需要给菜单关闭.
    togglemenu(500);
  }

  /**
   * 切换菜单
   * 参数:切换菜单的时间是可控的.
   */
  public void togglemenu(int duration) {
    //为所有子菜单添加动画. :平移动画丶旋转动画
    int count = getchildcount();
    for (int i = 0; i < count - 1; i++) {
      /**
       * 默认位置左上的话,子菜单起始坐标点为(-cl,-ct);
       *   位置右上的话,子菜单起始坐标点为(+cl,-ct);
       *   位置左下的话,子菜单起始坐标点为(-cl,+ct);
       *   位置右下的话,子菜单起始坐标点为(+cl,+ct);**
       * */
      final view childview = getchildat(i + 1);
      //不管按钮是开还是关,子菜单必须显示才能出现动画效果.
      childview.setvisibility(view.visible);
      //平移 结束为止 0,0(以子菜单按钮当前位置,为坐标系.)
      int cl = (int) (mradius * math.sin(math.pi / 2 / (count - 2) * i));
      int ct = (int) (mradius * math.cos(math.pi / 2 / (count - 2) * i));

      //创建两个判断变量,判别起始位置.
      int xflag = 1;
      int yflag = 1;
      if (mposition == position.left_top
          || mposition == position.left_bottom) {
        xflag = -1;
      }
      if (mposition == position.left_top
          || mposition == position.right_top) {
        yflag = -1;
      }
      //多个动画同时使用使用,用到animationset
      animationset animset = new animationset(true);
      animation trananim = null;

      //to open 打开的情况下
      if (mcurrentstatus == status.close) {
        trananim = new translateanimation(xflag * cl, 0, yflag * ct, 0);
        //当卫星菜单打开的时候,按钮就可以进行点击.
        childview.setclickable(true);
        childview.setfocusable(true);

      } else {//to close
        trananim = new translateanimation(0, xflag * cl, 0, yflag * ct);
        //当卫星菜单关闭的时候,按钮也不能随之点击.
        childview.setclickable(false);
        childview.setfocusable(false);
      }
      trananim.setfillafter(true);
      trananim.setduration(duration);
      //设置弹出速度.
      trananim.setstartoffset((i * 100) / count);
      //为动画设置监听 如果需要关闭的话,在动画结束的同时,需要将子菜单的按钮全部隐藏.
      trananim.setanimationlistener(new animation.animationlistener() {
        @override
        public void onanimationstart(animation animation) {

        }

        //在动画结束时,进行设置.
        @override
        public void onanimationend(animation animation) {
          if (mcurrentstatus == status.close) {
//            log.d("动画结束状态",mcurrentstatus +"");
            childview.setvisibility(view.gone);
          }
        }

        @override
        public void onanimationrepeat(animation animation) {

        }
      });

      //设置旋转动画(转两圈)
      rotateanimation rotateanim = new rotateanimation(0, 720,
          animation.relative_to_self, 0.5f,
          animation.relative_to_self, 0.5f);
      rotateanim.setduration(duration);
      rotateanim.setfillafter(true);

      //把两个动画放到动画集里面
      //注意动画顺序.先增加旋转/在增加移动./
      animset.addanimation(rotateanim);
      animset.addanimation(trananim);
      childview.startanimation(animset);

      final int pos = i + 1;
      //设置子菜单的点击事件
      childview.setonclicklistener(new onclicklistener() {
        @override
        public void onclick(view v) {
          if (mmenuitemclicklistener != null) {
            mmenuitemclicklistener.onclick(childview, pos);
          }
            menuitemanim(pos - 1);
            //切换菜单状态
            changestatus();
        }
      });
    }
    /**
     * 当所有子菜单切换完成后,那么菜单的状态也发生了改变.
     * 所以changestatus()必须放在循环外,
     * */
    //切换菜单状态
    changestatus();

  }


  /**
   * 切换菜单状态
   */
  private void changestatus() {
    //在执行一个操作之后,如果按钮是打开的在次点击就会切换状态.
    mcurrentstatus = (mcurrentstatus == status.close ? status.open :
        status.close);
    log.d("动画结束状态", mcurrentstatus + "");
  }

  public boolean isopen(){
    return mcurrentstatus ==status.open;
  }




  //设置旋转动画绕自身旋转一圈 然后持续时间为300
  private void rotatecbutton(view v, float start, float end, int duration) {
    rotateanimation anim = new rotateanimation(start, end, animation.relative_to_self, 0.5f, animation.relative_to_self, 0.5f);
    anim.setduration(duration);
    //保持动画旋转后的状态.
    anim.setfillafter(true);
    v.startanimation(anim);
  }

  /**
   * 添加menuitem的点击动画
   * */
  private void menuitemanim(int pos) {
    for (int i = 0; i < getchildcount() - 1; i++) {
      view childview = getchildat(i + 1);
      //在判断条件下,写入动画
      //当其中一个子菜单被点击后,自身变大并且消失
      //其他子菜单则变小消失.
      if (i == pos) {
        childview.startanimation(scalebiganim(300));
      } else {
        childview.startanimation(scalesmallanim(300));
      }

      //当子菜单被点击之后,其他子菜单就要变成不可被点击和获得焦点的状态,
      childview.setclickable(false);
      childview.setfocusable(false);
    }
  }

  /**
   * 为当前点击的item设置变大和透明度降低的动画
   *
   * @param duration
   * @return
   */
  private animation scalebiganim(int duration) {
    animationset animationset = new animationset(true);
    scaleanimation scaleanimation = new scaleanimation(1.0f, 4.0f, 1.0f, 4.0f,
        animation.relative_to_self, 0.5f,
        animation.relative_to_self, 0.5f);
    alphaanimation alphaanimation=new alphaanimation(1f,0.0f);

    animationset.addanimation(scaleanimation);
    animationset.addanimation(alphaanimation);

    animationset.setduration(duration);
    animationset.setfillafter(true);
    return animationset;
  }

  private animation scalesmallanim(int duration) {
    animationset animationset = new animationset(true);
    scaleanimation scaleanimation = new scaleanimation(1.0f, 0.0f, 1.0f, 0.0f,
        animation.relative_to_self, 0.5f,
        animation.relative_to_self, 0.5f);
    alphaanimation alphaanimation=new alphaanimation(1f,0.0f);
    animationset.addanimation(scaleanimation);
    animationset.addanimation(alphaanimation);
    animationset.setduration(duration);
    animationset.setfillafter(true);
    return animationset;
  }

}

以上就是 卫星菜单的编写,上面的注释量比较大。

这里需要注意的一点。卫星菜单在屏幕不同位置,他的动画平移值是不一样的。

如果实在不理解可以画图试试。

三、使用时注意赋予命名空间

<?xml version="1.0" encoding="utf-8"?>
<com.lanou.dllo.arcmenudemo.arcmenu.arcmenu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:arcmenu="http://schemas.android.com/apk/res/com.lanou.dllo.arcmenudemo"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/id_menu"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  arcmenu:position="left_top"
  arcmenu:radius="140dp"
>


    <!-- 主按钮-->
    <relativelayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@mipmap/composer_button">

      <imageview
        android:id="@+id/id_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerinparent="true"
        android:src="@mipmap/composer_icn_plus" />
    </relativelayout>


    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/composer_camera"
      android:tag="camera"/>

    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/composer_music"
      android:tag="music"/>

    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/composer_place"
      android:tag="place"/>

    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/composer_sleep"
      android:tag="sleep"/>

    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/composer_thought"
      android:tag="sun"/>

    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/composer_with"
      android:tag="people"/>

</com.lanou.dllo.arcmenudemo.arcmenu.arcmenu>

其他的大家可以自行探索研究。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网