標籤:標題列 prim 屬性 case 事件 開啟 protect bundle star
DrawerLayout是一個擁有兩個子控制項的布局,第一個子控制項是主畫面中顯示的內容,第二個子控制項是滑動菜單中顯示的內容:
1 <android.support.v4.widget.DrawerLayout 2 xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 android:id="@+id/drawer_layout" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 > 8 9 <FrameLayout10 android:layout_width="match_parent"11 android:layout_height="match_parent">12 13 <android.support.v7.widget.Toolbar14 android:id="@+id/toolbar"15 android:layout_width="match_parent"16 android:layout_height="?attr/actionBarSize"17 android:background="?attr/colorPrimary"18 android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"19 app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>20 21 </FrameLayout>22 <TextView23 android:layout_width="match_parent"24 android:layout_height="match_parent"25 android:layout_gravity="start"26 android:text="這是一個菜單"27 android:textSize="30sp"28 android:background="#FFF"/>29 </android.support.v4.widget.DrawerLayout>
要注意的地方是第二個子控制項TextView的layout_gravity屬性指定的是滑動菜單是在螢幕的左邊還是右邊,屬性值使用right或者left,這裡使用start表示根據系統語言進行判斷。
這裡的效果是這樣:
然後在標題列上加入一個導覽按鈕,點擊導覽按鈕也能開啟滑動菜單,具體實現原理是,標題列左方本來就有一個叫作HomeAsup的按鈕,它預設的表徵圖是一個返回的箭頭,含義是返回上一個活動,所以只需要將它顯示出來,修改它的表徵圖和點擊事件即可。
具體java代碼:
1 public class MainActivity extends AppCompatActivity { 2 3 private DrawerLayout mDrawerLayout; 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 9 setSupportActionBar(toolbar);10 mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);11 ActionBar actionBar = getSupportActionBar();12 if(actionBar != null){13 //讓ActionBar的HomeAsUp按鈕顯示出來14 actionBar.setDisplayHomeAsUpEnabled(true);15 //改變HomeAsUp按鈕的表徵圖16 actionBar.setHomeAsUpIndicator(R.drawable.ic_action_name);17 }18 19 }20 ...21 public boolean onOptionsItemSelected(MenuItem item){22 switch (item.getItemId()){23 case android.R.id.home:24 mDrawerLayout.openDrawer(GravityCompat.START);25 break;26 ...27 default:28 break;29 }30 return true;31 }32 }
android ——滑動菜單