Android实现自定义左右菜单
功能描述:
在左中右三个区域分别承载三个不同的view,把它全部添加进来,而我们实现左右菜单,就是来控制当前显示的是哪一部分;如果显示中间菜单,就把中间菜单呈现在用户面前;如果显示左菜单,就把左菜单和一部分的中间菜单呈现在用户面前;如果显示右菜单,就把右菜单和一部分的中间菜单呈现在用户面前。即整张图的左中右不断移动。
功能实现(step by step):
1、菜单布局(通过扩展,完成基本布局。包含左右菜单布局和中间内容区域,并设置颜色用于区分)2、菜单左右滑动(使用逻辑,找出滑动中间点,并对事件作处理,主要针对滑动事件)3、加入左右滑动动画(使用Scroll进行滑动事件处理,主要是自动滑动,增加用户体验)4、处理点击事件(通过对左右事件的处理,会阻止点击事件的处理,这里需要调用系统,返还点击事件)5、添加蒙板效果(通过增加view,对view的透明度进行处理,从而实现蒙版效果)
核心内容:
1.布局的添加
2.事件分发机制
3.滚动添加
4.蒙版添加
构想图:
开发过程中遇到的错误:
Caused by:java.lang.IllegalStateException:The specified child already has a parent.You must call removeView() on the child’s parent first.
造成这个原因,是组件在父类中重复加载了相同的组件
如:
addView(leftMenu, mLayout); // 第一次添加
addView((leftMenu, , mLayout); // 第二次添加
源代码:
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools= "http://schemas.android.com/tools"
android:layout_width= "match_parent"
android:layout_height= "match_parent"
tools:context= ".MainActivity" >
</RelativeLayout>
left.xml:
<?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= "match_parent"
android:orientation= "vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height=