<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mydrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!--注意:抽屉布局中 定义的第一个组件最好是 主内容布局 第二个是 菜单内容布局
否则:如果菜单中ListView列表的话,会造成没有组件没焦点的问题-->
<!--主内容区域-->
<RelativeLayout
android:id="@+id/fr_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<!--菜单-->
<LinearLayout
android:id="@+id/lin_menu"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#f00"
android:orientation="vertical"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher_round" />
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
————————————————————————————————————————————————————
package zhanghaijiao.bawei.com.drawerlayout_demo1;
import android.Manifest;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private LinearLayout linMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//抽屉布局
drawerLayout = findViewById(R.id.mydrawer);
//菜单
linMenu = findViewById(R.id.lin_menu);
Button btnOpen=findViewById(R.id.btn_open);
btnOpen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//打开菜单
drawerLayout.openDrawer(linMenu);
//关闭菜单
// drawerLayout.closeDrawer(linMenu);
}
});
//设置监听事件
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
//滑动菜单时调用的方法
//slideOffset 表示 滑动的幅度(0-1)
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
Log.d("zzz","slideOffset:"+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();
}
//菜单状态被改变时调用 idle-空闲 0 draggle-拖拽 1 settling-固定 2
@Override
public void onDrawerStateChanged(int newState) {
Log.d("zzz","newState:"+newState);
}
});
}
}