Toolbar 加 DrawerLayout 簡單使用實現側滑選單
阿新 • • 發佈:2018-12-17
佈局檔案
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout android:id="@+id/dw" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.administrator.toolbaranddrawerlayout.MainActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" ></android.support.v7.widget.Toolbar> </RelativeLayout> <!--DrawerLayout側滑中設定左側滑動設定屬性為: android:layout_gravity="start" , 設定右側滑動屬性為:android:layout_gravity="end" 本文設定的為右側滑動--> <RelativeLayout android:id="@+id/rl" android:background="@color/colorPrimary" android:layout_gravity="end" android:layout_width="200dp" android:layout_height="match_parent"></RelativeLayout> </android.support.v4.widget.DrawerLayout>
設定Toolbar:Toolbar是安卓自帶的不需要導包 但是需要把AndroidManifest 中Android:theme屬性改變一下否則Toolbar不會顯示出來
//替換前
android:theme="@style/AppTheme"
//替換後
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
Mainactivity中實現效果
package com.example.administrator.toolbaranddrawerlayout; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private DrawerLayout dw; private RelativeLayout right; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); //新增圖示 toolbar.setLogo(R.drawable.ic_launcher_background); toolbar.setTitle("主標題"); toolbar.setSubtitle("副標題"); setSupportActionBar(toolbar); //新增左側點選圖示(注意需要在setSupportActionBar(toolbar)之後才有效果) toolbar.setNavigationIcon(R.mipmap.ic_launcher); //為左側圖示設定點選事件 toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //判斷該控制元件是否已經開啟 if (dw.isDrawerOpen(right)){ dw.closeDrawer(right); }else { dw.openDrawer(right); } } }); } private void initView() { toolbar = (Toolbar) findViewById(R.id.toolbar); dw = (DrawerLayout) findViewById(R.id.dw); right = (RelativeLayout) findViewById(R.id.rl); } }