actionBar和DrawerLayout的使用(抽屉布局)

activity_main.xml布局


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:id="@+id/drawer_layout"
    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="Hello World!"/>
    RelativeLayout>

    
    <FrameLayout
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white">

    FrameLayout>

android.support.v4.widget.DrawerLayout>

MainActivity代码


public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initActionBar();
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);  //ActionBarHome位置可以点击

        //获取抽屉布局对象
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        //创建一个抽屉开关,用于控制抽屉的开和关.后两个参数用于指定打开和关闭抽屉的描述,如果不需要填0
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);

        drawerToggle.syncState();   //同步ActionBar和抽屉布局的状态

        //给抽屉布局设置监听器,用于监听抽屉的滑动
        drawerLayout.addDrawerListener(drawerToggle);
    }

    /**
     * 当菜单选项被点击的时候会执行
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        drawerToggle.onOptionsItemSelected(item);   //使用抽屉开关来控制抽屉的开和关
        return super.onOptionsItemSelected(item);
    }
}

你可能感兴趣的:(android)