MainActivity.java
package com.example.drawablelayot;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
private DrawerLayout mDrawerLayout; //根布局
private LinearLayout ll_drawer; //侧滑栏布局
private TextView tv;
private Button btn_drawer;
private ImageView iv_drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
ll_drawer = (LinearLayout) findViewById(R.id.ll_drawerLeft);
btn_drawer = (Button) findViewById(R.id.btn_drawerLeft);
iv_drawer = (ImageView) findViewById(R.id.iv_drawerLeft);
btn_drawer.setOnClickListener(this); //可以直接对侧滑栏控件进行操作
iv_drawer.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_drawerLeft:
tv.setText("点击了按钮");
mDrawerLayout.closeDrawer(ll_drawer); //把侧滑栏ll_drawer关闭
break;
case R.id.iv_drawerLeft:
tv.setText("点击了头像图片");
mDrawerLayout.closeDrawer(ll_drawer);
break;
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 第一个View表示主布局 -->
<RelativeLayout
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="这是主布局"/>
</RelativeLayout>
<!-- 第二个View表示侧滑菜单的布局 -->
<LinearLayout
android:id="@+id/ll_drawerLeft"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffcc"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_drawerLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/psb"/>
<Button
android:id="@+id/btn_drawerLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是一个按钮"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>