Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidのActionBarでNavigationViewを実装する方法【初心者向け解説】

NavigationViewとは?

NavigationViewの実装例に入る前に、まずはNavigationViewについて理解しておきましょう。NavigationViewとは、HTMLにおけるスライドメニューのようなもので、画面端からスライドして表示されるナビゲーションメニューです。NavigationViewはNavigationDrawer(ナビゲーションドロワー)を拡張したコンポーネントであり、主な用途としては、別のアクティビティへの遷移やプロフィール情報の表示などが挙げられます。

本記事では、ActionBarにNavigationViewを組み込む方法を、ステップバイステップで詳しく解説します。

ステップ1:新規プロジェクトの作成

Android Studioを起動し、「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。

ステップ2:Navigation Drawer Activityの選択

プロジェクト作成時に、下図のように「Navigation Drawer Activity」を選択してください。その後「Next」ボタンをクリックして、プロジェクトの作成を完了させます。

AndroidのActionBarでNavigationViewを実装する方法【初心者向け解説】

ステップ3:生成されるレイアウトファイルの確認

プロジェクト構造のlayoutフォルダを開くと、Android Studioが自動的に複数のレイアウトファイルを生成していることがわかります。それぞれの役割を見ていきましょう。

activity_main.xml

これはMainActivity用のレイアウトファイルです。親レイアウトとしてDrawerLayoutを作成し、子レイアウトとしてNavigationViewを配置します。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    xmlns:tools = "https://schemas.android.com/tools"
    android:id = "@+id/drawer_layout"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:fitsSystemWindows = "true"
    tools:openDrawer = "start">
    <include
        layout = "@layout/app_bar_main"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent" />
    <android.support.design.widget.NavigationView
        android:id = "@+id/nav_view"
        android:layout_width = "wrap_content"
        android:layout_height = "match_parent"
        android:layout_gravity = "start"
        android:fitsSystemWindows = "true"
        app:headerLayout = "@layout/nav_header_main"
        app:menu = "@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

NavigationViewには「Header Layout(ヘッダーレイアウト)」と「Menu Layout(メニューレイアウト)」の2つのレイアウトが含まれています。ヘッダーレイアウトにはNavigationViewのヘッダー部分の情報が格納され、メニューレイアウトにはメニューリストの情報が格納されます。

app_bar_main.xml

通常のレイアウトファイルと同様の形式ですが、AppBarLayout(アクションバー)や中央のコンテンツレイアウトに関する情報が含まれています。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">
    <android.support.design.widget.AppBarLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:theme = "@style/AppTheme.AppBarOverlay">
    <android.support.v7.widget.Toolbar
        android:id = "@+id/toolbar"
        android:layout_width = "match_parent"
        android:layout_height = "?attr/actionBarSize"
        android:background = "?attr/colorPrimary"
        app:popupTheme = "@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
    <include layout = "@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>

上記のレイアウトではcontent_mainレイアウトを読み込んでいます。このcontent_mainが、ユーザーが自由に独自のビューをカスタマイズできるメインレイアウトです。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    app:layout_behavior = "@string/appbar_scrolling_view_behavior"
    tools:context = ".MainActivity"
    tools:showIn = "@layout/app_bar_main">
    <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Hello World!"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

nav_header_main.xml

これはナビゲーションのヘッダービューで、ヘッダー部分の情報を保持します。以下のようにヘッダーをカスタマイズできます。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    android:layout_width = "match_parent"
    android:layout_height = "@dimen/nav_header_height"
    android:background = "@drawable/side_nav_bar"
    android:gravity = "bottom"
    android:orientation = "vertical"
    android:paddingLeft = "@dimen/activity_horizontal_margin"
    android:paddingTop = "@dimen/activity_vertical_margin"
    android:paddingRight = "@dimen/activity_horizontal_margin"
    android:paddingBottom = "@dimen/activity_vertical_margin"
    android:theme = "@style/ThemeOverlay.AppCompat.Dark">
    <ImageView
        android:id = "@+id/imageView"
        android:layout_width = "wrap_content"
        android:layout_height = "100dp"
        android:contentDescription = "@string/nav_header_desc"
        android:paddingTop = "@dimen/nav_header_vertical_spacing"
        app:srcCompat = "@drawable/logo" />
    <TextView
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:paddingTop = "@dimen/nav_header_vertical_spacing"
        android:textColor = "#FFF"
        android:textStyle = "bold"
        android:text = "Tutorials Point"
        android:textAppearance = "@style/TextAppearance.AppCompat.Body1" />
    <TextView
        android:id = "@+id/textView"
        android:textColor = "#FFF"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Father of all educational website" />
</LinearLayout>

注意: ここではdrawable/logoを追加していますが、実際にアプリを開発する際はご自身のロゴ画像を使用してください。

activity_main_drawer.xml

これはmenu/activity_main_drawer.xmlに配置されるメニューレイアウトです。以下のような内容になっています。

<?xml version = "1.0" encoding = "utf-8"?>
<menu xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:tools = "https://schemas.android.com/tools"
    tools:showIn = "navigation_view">
    <group android:checkableBehavior = "single">
        <item
            android:id = "@+id/nav_camera"
            android:icon = "@drawable/ic_menu_camera"
            android:title = "Import" />
        <item
            android:id = "@+id/nav_gallery"
            android:icon = "@drawable/ic_menu_gallery"
            android:title = "Gallery" />
        <item
            android:id = "@+id/nav_slideshow"
            android:icon = "@drawable/ic_menu_slideshow"
            android:title = "Slideshow" />
        <item
            android:id = "@+id/nav_manage"
            android:icon = "@drawable/ic_menu_manage"
            android:title = "Tools" />
    </group>
    <item android:title = "Communicate">
        <menu>
            <item
                android:id = "@+id/nav_share"
                android:icon = "@drawable/ic_menu_share"
                android:title = "Share" />
            <item
                android:id = "@+id/nav_send"
                android:icon = "@drawable/ic_menu_send"
                android:title = "Send" />
        </menu>
    </item>
</menu>

ステップ4:MainActivity.javaへのコード追加

src/MainActivity.javaに以下のコードを追加します。

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // メニューをインフレートし、アクションバーにアイテムを追加します
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // アクションバーのアイテムクリックをここで処理します。
        // Home/Upボタンのクリックは、AndroidManifest.xmlで親アクティビティを
        // 指定していれば自動的に処理されます。
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // NavigationViewのアイテムクリックをここで処理します。
        int id = item.getItemId();
        if (id == R.id.nav_camera) {
            // カメラアクションの処理
        } else if (id == R.id.nav_gallery) {
        } else if (id == R.id.nav_slideshow) {
        } else if (id == R.id.nav_manage) {
        } else if (id == R.id.nav_share) {
        } else if (id == R.id.nav_send) {
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

ドロワーの開閉と位置の制御

NavigationViewを閉じるには、以下のようにドロワーを閉じます。

if (drawer.isDrawerOpen(GravityCompat.START)) {
    drawer.closeDrawer(GravityCompat.START);
}

また、NavigationViewの表示位置を変更したい場合は、次のコードを使用します。

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続していることを前提とします。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。オプションから接続したモバイルデバイスを選択すると、実機の画面にデフォルトの画面が表示されます。

AndroidのActionBarでNavigationViewを実装する方法【初心者向け解説】

  1. ActionBarActivityでActionBarの背景色を変更する方法

    この記事では、ActionBarActivityのActionBar(アクションバー)の背景色を変更する手順について解説します。テーマのスタイル定義を編集することで、アプリ全体のデザインに合わせたカスタマイズが可能になります。ステップ1:新規プロジェクトの作成Android Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトのセットアップを完了させてください。ステップ2:レイアウトファイルの編集res/layout/activity_main.xmlに以下のコードを追加します。<?xml vers

  2. 【Android】NavigationViewの実装方法をステップごとに解説

    この記事では、AndroidアプリでNavigationView(ナビゲーションビュー)を使用してドロワーメニューを実装する方法を、ステップごとに詳しく解説します。ハンバーガーアイコンから開閉できるサイドメニューは、多くのアプリで採用されている定番のUIです。ステップ1:新しいプロジェクトを作成するAndroid Studioを開き、File → New Project を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートには「Navigation Drawer Activity」を選ぶと、後の作業がスムーズになります。ステップ2:activity_main.xml にコ