DrawLayout控件是Google提供的一种实现侧滑效果的控件,使用该控件可以很容易地实现侧滑菜单的效果,因为是系统自带的,
所以不需要导入第三方的框架。
我们直接看下activity_main.xml文件吧:
<?xml version="1.0" encoding="utf-8"?>
<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">
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--内容区-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DrawLayout内容区" />
</RelativeLayout>
<!-- android:layout_gravity="start" 设置界面左边边显示-->
<LinearLayout
android:id="@+id/leftLayout"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#f00"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="左边的按钮" />
</LinearLayout>
<!-- android:layout_gravity="end" 设置界面右边显示-->
<LinearLayout
android:id="@+id/rightLayout"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#0f0"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="右边的按钮" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
这样就可以实现侧滑菜单效果了,当然我们也可以在MainActivity中设置其相应的监听事件:
package com.example.administrator.myapplication02;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (DrawerLayout) findViewById(R.id.drawLayout);
layout.setDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
Toast.makeText(MainActivity.this, "打开侧边栏了", Toast.LENGTH_SHORT).show();
}
@Override
public void onDrawerClosed(View drawerView) {
Toast.makeText(MainActivity.this, "关闭侧边栏了", Toast.LENGTH_SHORT).show();
}
@Override
public void onDrawerStateChanged(int newState) {
}
});
}
}
运行结果: