- 公開日:2015年09月23日
記事概要
AndroidのNavigationViewでheaderを実装する方法を記載した記事です
環境
- Android Studio 1.3.0
- OS X Yosemite
- android sdk 23(Android 6.0 Marshmallow(マシュマロ))
- com.android.support:design:23.0.0
はじめに
ライブラリに、com.android.support:design:23.0.0を利用します。とても便利なgoogle純正のライブラリです。
適用するアプリとして、山情報アプリのマウンテンチャンネルを使います。
layout xmlの実装
まずは以下のようにlayoutを実装します。
<android.support.v4.widget.DrawerLayout
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"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_items" />
</android.support.v4.widget.DrawerLayout>
上記のように実装すると、以下の様な画面を表示できます。
Headerの実装
続いてNavigationViewにheaderを実装します。xmlで指定しても良いのですが、今回は固定データのheaderでなく、認証したユーザー情報を表示するヘッダーを表示したいのでinflateHeaderViewでheaderのviewを生成して作成します。
drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/default_theme_color" >
<com.ui.widget.BezelImageView
android:id="@+id/user_image"
app:maskDrawable="@drawable/circle_mask"
android:layout_width="@dimen/expert_icon_size"
android:layout_height="@dimen/expert_icon_size"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/user_name"
android:layout_below="@id/user_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="@android:color/black" />
</RelativeLayout>
java
private DrawerLayout drawerLayout;
private TextView mUserName;
private BezelImageView mUserImage;
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
// header view inflate
View drawerLayout = navigationView.inflateHeaderView(R.layout.drawer_header);
mUserName = (TextView)drawerLayout.findViewById(R.id.user_name);
mUserImage = (BezelImageView)drawerLayout.findViewById(R.id.user_image);
findByIdではなく、inflateHeaderViewを呼び出すことに注意してください。
headerデータが固定情報でない場合、直接xmlにデータを指定できません。
なので、APIから習得するユーザー情報等を表示したい場合は、inflateHeaderViewを利用します。googleのチュートリアルには記載されていないので気をつけてください。
以上
Androidアプリ【マウンテンチャンネル】


0 件のコメント:
コメントを投稿