您的位置:首页 > 移动开发 > Android开发

android抽屉DrawerLayout的使用

2015-03-25 17:50 369 查看
DrawerLayout是存在于v4包下的类,主要实现android抽屉的效果.

使用的原理是将抽屉展现的布局控件摆放在屏幕的右边或者左边.(展现的位置不在屏幕上).通过

android:layout_gravity=”right”来控制.

然后调用抽屉的方法来将该布局展现或者消失,达到抽屉的效果.

xml文件的代码:

[code] <android.support.v4.widget.DrawerLayout 
android:id="@+id/drawerLayout"
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"
 >

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout"
    >
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="open"
        android:text="开启"
        android:layout_gravity="right"
        />
</LinearLayout>

 <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout"
    //摆放在屏幕的最左边
    android:layout_gravity="right"
    >
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="close"
        android:text="关闭"
        android:layout_gravity="right"
        />
</LinearLayout>     
</android.support.v4.widget.DrawerLayout>


按钮的点击事件来处理展现或者消失:

[code] //展现
public void open(View view){
    drawer.openDrawer(Gravity.RIGHT);
}

//消失
public void close(View view){
    drawer.closeDrawer(Gravity.RIGHT);
}


当我们点击抽屉的空白区域的时候,会出现一个现象,那就是会操作抽屉覆盖的Activity的控件,这不是我们想要的结果,那么如何处理呢?首先,我们先判断抽屉是否被打开或者被关闭,然后根据抽屉的状态,处理Activity的触摸事件.

[code] listview.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // TODO Auto-generated method stub

                    if(getActivity() instanceof IndexActivity){
                        IndexActivity activity=(IndexActivity) getActivity();
                        //判断抽屉是否被打开
                        boolean open=activity.IsDrawerOpen();
                        if(open){
                            event.setAction(MotionEvent.ACTION_CANCEL);
                            return false;
                        }else{
                            return v.onTouchEvent(event);
                        }
                    }
                    return false;
                }
            });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: