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

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

この記事では、AndroidアプリでNavigationView(ナビゲーションビュー)を使用してドロワーメニューを実装する方法を、ステップごとに詳しく解説します。ハンバーガーアイコンから開閉できるサイドメニューは、多くのアプリで採用されている定番のUIです。

ステップ1:新しいプロジェクトを作成する

Android Studioを開き、File → New Project を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートには「Navigation Drawer Activity」を選ぶと、後の作業がスムーズになります。

ステップ2:activity_main.xml にコードを追加する

res/layout/activity_main.xml に以下のコードを記述します。全体を DrawerLayout で囲み、その中に NavigationView とメインコンテンツ(app_bar_main)を配置する構成です。

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
    <com.google.android.material.navigation.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" />
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>

ポイントは、NavigationView の android:layout_gravity="start" を指定することで、画面の左側からスライド表示されるようになる点です。また、app:headerLayout でヘッダー部分のレイアウトを、app:menu でメニュー項目を定義したXMLファイルを指定しています。

ステップ3:MainActivity.java にコードを追加する

src/MainActivity.java に以下のコードを記述します。ToolbarやFloatingActionButtonの設定に加え、NavControllerとNavigationViewを連携させることで、メニュー選択時の画面遷移を自動的に処理できるようになります。

import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
    private AppBarConfiguration mAppBarConfiguration;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_tools, R.id.nav_share,
            R.id.nav_send).setDrawerLayout(drawer).build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
    }
}

ステップ4:fragment_home.xml を作成する

レイアウトリソースファイル(fragment_home.xml)を新規作成し、以下のコードを記述します。ホーム画面として表示するTextViewを含むシンプルなレイアウトです。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="match_parent">
    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

ステップ5:HomeFragment.java を作成する

Javaクラス(HomeFragment.java)を新規作成し、以下のコードを追加します。ViewModelから取得したテキストを、LiveDataのオブザーバー経由でTextViewに反映する構成になっています。

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import app.com.myapplication.R;
public class HomeFragment extends Fragment {
    private HomeViewModel homeViewModel;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

ステップ6:HomeViewModel.java を作成する

次に、Javaクラス(HomeViewModel.java)を新規作成します。Fragmentが画面回転などで再生成されてもデータを保持できるよう、ViewModelにテキストデータを持たせます。

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class HomeViewModel extends ViewModel {
    private MutableLiveData<String> mText;
    public HomeViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("This is home fragment");
    }
    public LiveData<String> getText() {
        return mText;
    }
}

ギャラリー、共有、送信などの他のメニュー項目についても、同様の手順でFragmentとViewModelを作成してください。その際、クラス名やリソースIDの命名規則(nav_home、nav_gallery など)を統一することが非常に重要です。命名がステップ3の AppBarConfiguration で指定したIDと一致していないと、画面遷移が正しく動作しません。

ステップ7:AndroidManifest.xml にコードを追加する

androidManifest.xml に以下のコードを記述します。MainActivity をランチャーアクティビティとして登録し、NoActionBarテーマを適用しています。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.myapplication">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して確認する

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

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

左端からスワイプ、またはツールバーのハンバーガーアイコンをタップすると、NavigationViewのドロワーメニューが開き、各メニュー項目を選択して画面を切り替えられます。これで、AndroidアプリへのNavigationViewの実装は完了です。

  1. 【Android】ViewFlipperの使い方を徹底解説!ビュー切り替えアニメーションの実装方法

    ViewFlipperとは?ViewFlipperは、複数の子ビューを重ねて保持し、一定間隔での自動切り替えやボタン操作による手動切り替えを、アニメーション効果付きで実現できるAndroidのウィジェットです。画像スライダー、オンボーディング画面、シンプルなカルーセルUIなどを作りたいときに非常に便利です。本記事では、ViewFlipperを使ってImageView・Button・TextViewをスライドアニメーションで切り替えるサンプルアプリを、ステップごとに詳しく解説します。Step 1:新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New

  2. 【Android】スナックバー(Snackbar)の使い方をステップごとに解説

    このチュートリアルでは、Androidアプリでスナックバー(Snackbar)を使用する方法を、サンプルコードとともに段階的に解説します。スナックバーは画面下部に短いメッセージを一時的に表示できるUIコンポーネントで、Toastとは異なり「再試行(RETRY)」などのアクションボタンを組み込めるのが大きな特徴です。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(activity_main.xml)を編集する