Android仿印象笔记的自定义菜单控件
导读
今天在慕课网上看到一篇视频教程,Android实现卫星菜单,感觉效果非常炫酷,想到印象笔记添加笔记的菜单也可以通过这种方式来实现,点击添加笔记菜单按钮,便会弹出一系列的按钮用于添加不同的笔记。于是自己试着仿照印象笔记的菜单按钮,写出一个自定义的菜单控件。
效果图
先上一下效果图,看看完成后的效果如何
准备图片资源
我们先准备一下自定义菜单所需要的资源。Google发布了Material Design Icons,正好可以被我们拿来用,下载地址Material Design icon合集 ,选出我们需要的图标拷贝到Android Studio里。
自定义控件attr属性
首先,我们需要编写自定义控件的属性。在values文件夹下添加attr.xml文件,代码如下:
<declare-styleable name="MyMenu">
<attr name="position">
<enum name="left_top" value="0"/>
<enum name="right_top" value="1"/>
<enum name="left_bottom" value="2"/>
<enum name="right_bottom" value="3"/>
</attr>
<attr name="interval" format="dimension"/>
</declare-styleable>
自定义属性中包含两个属性,第一个是position,记录菜单在屏幕中所处的位置,第二个是interval,记录菜单展开后,每个按钮之间的间隔。
在XML文件中使用自定义控件
在XML文件中使用自定义菜单之前,需要新建MyMenu类,让它继承ViewGroup。实现MyMenu类的构造方法和onLayout方法,确保不报错即可。具体代码请看下一节内容。
新建一个布局文件,Android Studio会自动引用命名空间,所以可以直接写我们的自定义控件。我在自定义控件中增加了一个主按钮ImageView,四个子按钮LinearLayout,具体代码如下所示:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.phoenix.myapplication.MyMenu
android:layout_width="match_parent"
android:layout_height="match_parent"
app:interval="100dp"
app:position="right_bottom">
<ImageView
android:id="@+id/id_mainButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_add_circle_black_48dp"/>
<LinearLayout
android:id="@+id/id_item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="item1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item1"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_archive_grey600_48dp"/>
</LinearLayout>
<LinearLayout
android:id="@+id/id_item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="item2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item2"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_backspace_grey600_48dp"/>
</LinearLayout>
<LinearLayout
android:id="@+id/id_item3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag=