把主的布局修改为android.support.v4.widget.DrawerLayout
2:然后添加两个LinearLayout的布局,在第二个里面添加一个参数android:layout_gravity="left|start",千万记住了,这里是layout_gravity而不是gravity这样就可以实现抽屉的作用了
布局如下:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:id="@+id/drawable" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <LinearLayout android:background="#6660" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Hello World, Kodulf is a good Programmer\n Hello World, Kodulf is a good Programmer"/> </LinearLayout> <LinearLayout android:layout_gravity="left|start" android:background="#6066" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/menu"></LinearLayout> </android.support.v4.widget.DrawerLayout>
MainActivity的内容如下:
package tech.androidstudio.slidingpandlayoutdemo; import android.support.v4.view.GravityCompat; 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.MenuItem; import android.view.View; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private DrawerLayout mDrawerLayout; private LinearLayout mMenu; private ActionBarDrawerToggle mToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDrawerLayout = (DrawerLayout)findViewById(R.id.drawable); //获取第二LinearLayout,这个在布局里面设置了最关键的属性android:layout_gravity="left|start" mMenu = (LinearLayout)findViewById(R.id.menu); mMenu.setOnClickListener(this); //考虑 ActionBar和DrawerLayout的联动 mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //三条横线的Menu mToggle.syncState(); mDrawerLayout.setDrawerListener(mToggle);//让DrawerLayout的动作影响上面的按钮 } @Override public void onClick(View v) { //可以有两种方法来收回抽屉 mDrawerLayout.closeDrawer(mMenu); //mDrawerLayout.closeDrawer(Gravity.START);;//4.0一下是不能使用START的 //mDrawerLayout.closeDrawer(GravityCompat.START); } //如果不写这个方法,只能实现DrawerLayout 来控制ActionBar的Toggle //写了这个方法,就能够实现点击 Toggle以后 DrawerLayout变化 @Override public boolean onOptionsItemSelected(MenuItem item) { if(mToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } }