Android中实现简单的DrawerLayout

//布局文件

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#0f0"
    android:orientation="vertical"
    android:padding="10dp">

    <Button
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="页面一"
        android:textSize="20sp" />

    <Button
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="页面二"
        android:textSize="20sp" />
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>


//实现简单的侧拉
public class MainActivity extends AppCompatActivity {
	 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
	//找控件
	drawer = (DrawerLayout) findViewById(R.id.drawer);
	//ActionBar
    initAction();
  }
  
 //ActionBar
private void initAction() {

//import android.support.v7.app.ActionBar下的getSupportActionBar()

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    toggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
    toggle.syncState();
    drawer.addDrawerListener(toggle);
}

//侧滑点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (toggle.onOptionsItemSelected(item)) {
        return true;
    }
    return false;
}

}

猜你喜欢

转载自blog.csdn.net/wzj_8899174/article/details/83374324