在這個教程中,我們將在我們的Android應用程序中實現一個導航抽屜。Android導航抽屜是一個滑動菜單,是一個重要的UI組件。你會在大多數的Android應用程序中看到導航抽屜,它就像網站中的導航菜單欄一樣。
Android導航抽屜
Android導航抽屜是一個滑動的左側菜單,用於顯示應用程序中的重要鏈接。導航抽屜使得在這些鏈接之間來回導航變得容易。它默認情況下是不可見的,需要通過從左側滑動或點擊其圖標在操作欄中打開。在更廣泛的意義上,導航抽屜是一個覆蓋面板,它取代了一個專門用於顯示應用程序中所有選項和鏈接的活動屏幕。在這個Android導航抽屜教程中,我們將使用Android支援庫中的Drawer Layout API來實現導航抽屜。我們將展示3個片段視圖,可以從抽屜項目中打開。
Android導航抽屜項目結構
Android 導航抽屜範例
要實現導航抽屜,我們首先需要將android.support.v4.widget.DrawerLayout
添加為活動佈局的根,如下所示。activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
導航抽屜中的菜單選項以ListView的形式存儲。每個選項都在FrameLayout中打開。我們在這裡使用了一個ToolBar來替代ActionBar。ToolBar自Android 5.0引入以來被作為ActionBar的泛化。它為我們提供了更多的控制和靈活性來修改,並且更容易與層次結構中的其他視圖交錯。下面的xml佈局中定義了ToolBar的佈局。toolbar.xml
<android.support.v7.widget.Toolbar xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:local="https://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
在使用ToolBar時,我們需要在styles.xml中使用主題Theme.AppCompat.NoActionBar
。導航抽屜中的ListView行的佈局如下所示。list_view_item_row.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:padding="10dp" >
<ImageView
android:id="@+id/imageViewIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingRight="10dp" />
<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/imageViewIcon"
android:paddingRight="10dp"
android:text="Item Name"
android:textColor="@android:color/black"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
/>
</RelativeLayout>
導航抽屜項目被放在strings.xml文件中的字符串數組中,如下所示。strings.xml
<string-array name="navigation_drawer_items_array">
<item>Connect</item>
<item>Fixtures</item>
<item>Table</item>
</string-array>
DataModel.java類用於定義抽屜列表項的對象。DataModel.java
package com.journaldev.navigationdrawer;
public class DataModel {
public int icon;
public String name;
// Constructor.
public DataModel(int icon, String name) {
this.icon = icon;
this.name = name;
}
}
抽屜項目以ListView的形式存儲。因此,我們需要使用一個Adapter類來為活動類提供數據。DrawerItemCustomAdapter.java
package com.journaldev.navigationdrawer;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DrawerItemCustomAdapter extends ArrayAdapter<DataModel> {
Context mContext;
int layoutResourceId;
DataModel data[] = null;
public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, DataModel[] data) {
super(mContext, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
listItem = inflater.inflate(layoutResourceId, parent, false);
ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon);
TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName);
DataModel folder = data[position];
imageViewIcon.setImageResource(folder.icon);
textViewName.setText(folder.name);
return listItem;
}
}
MainActivity.java源碼如下:MainActivity.java
package com.journaldev.navigationdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.AdapterView;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
Toolbar toolbar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
setupToolbar();
DataModel[] drawerItem = new DataModel[3];
drawerItem[0] = new DataModel(R.drawable.connect, "Connect");
drawerItem[1] = new DataModel(R.drawable.fixtures, "Fixtures");
drawerItem[2] = new DataModel(R.drawable.table, "Table");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerToggle);
setupDrawerToggle();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView > parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ConnectFragment();
break;
case 1:
fragment = new FixturesFragment();
break;
case 2:
fragment = new TableFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
void setupToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
void setupDrawerToggle(){
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.app_name, R.string.app_name);
//這是在狀態變更時更改抽屜切換圖示的必要步驟。
mDrawerToggle.syncState();
}
}
在上述代碼中,getSupportActionBar().setDisplayHomeAsUpEnabled(false);
用於隱藏默認的返回按鈕。在此代碼中,我們使用了一個 DrawerItemClickListener
類,該類使用 FragmentManager 載入點擊的列表項相應的片段。同時,使用 setTitle(mNavigationDrawerItemTitles[position]);
將工具欄的標題更改為點擊的列表項。片段類及其相應的佈局如下。 ConnectFragment.java
package com.journaldev.navigationdrawer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConnectFragment extends Fragment {
public ConnectFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_connect, container, false);
return rootView;
}
}
上述片段的佈局如下所定義。 fragment_connect.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/label"
android:layout_alignParentTop="true"
android:layout_marginTop="100dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="45dp"
android:text="Connect"
android:textStyle="bold"/>
<TextView
android:layout_below="@id/label"
android:layout_centerInParent="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="12dp"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:text="Edit fragment_connect.xml to change the appearance"
android:id="@+id/textView2" />
</RelativeLayout>
其他兩個項目的定義方式完全相同,因此在此跳過。
導航抽屜Android示例輸出
以下是我們的導航抽屜Android示例應用程式生成的輸出。 這結束了Android導航抽屜示例教程。您可以從以下鏈接下載最終的 Android導航抽屜項目。
Source:
https://www.digitalocean.com/community/tutorials/android-navigation-drawer-example-tutorial