読者です 読者をやめる 読者になる 読者になる

うさがにっき

読書感想文とプログラムのこと書いてきます

ActionBarを使ってNavigationDrawerレイアウトを作成

ActionBarを使ってNavigationDrawerレイアウトを作成(NavigationDrawerFragment.NavigationDrawerCallbacks使用した場合)

概要

ActionBarを使ってNavigationDrawerレイアウトを作成する
NavigationDrawerを使うときはアプリが複雑な画面遷移を持つとき

最小構成

Eclipseのプロジェクト作成からNavigationDrawerレイアウトを選択すればすぐひな形が出来る

途中までタブレイアウトのときと同じ
f:id:tiro105:20140410123849p:plain
Navigtion TypeをにNavigationDrawerを設定しFinish

これでNavigation Drawerレイアウトのアプリが実行できるはず

ソースの確認

Activityレイアウト

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.navigationdrawertest.MainActivity" >

    <!--
         As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions.
    -->

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--
         android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead.
    -->
    <!--
         The drawer is given a fixed width in dp and extends the full height of
         the container.
    -->

    <fragment
        android:id="@+id/navigation_drawer"
        android:name="com.example.navigationdrawertest.NavigationDrawerFragment"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start" />

</android.support.v4.widget.DrawerLayout>

先にコンテンツのレイアウトを定義
その後にNavigationDrawer内のレイアウトを定義
今回はfragmentを定義しているが、listviewでもtextviewでもOK

NavigationDrawerのfragmentのレイアウト

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#cccc"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    tools:context="com.example.navigationdrawertest.NavigationDrawerFragment" />

listviewおいてるだけ

logic
Activity

public class MainActivity extends ActionBarActivity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks {

appcompatを使っているのでActionBarActivityを継承
fragmentからのNavigationDrawer内のアイテム選択時のイベントを処理するためにNavigationDrawerCallbacksを実装

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
			.findFragmentById(R.id.navigation_drawer);
	mTitle = getTitle();

	// Set up the drawer.
	mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
			(DrawerLayout) findViewById(R.id.drawer_layout));
}

fragmentの取得、設定など

@Override
public void onNavigationDrawerItemSelected(int position) {
	// update the main content by replacing fragments
	FragmentManager fragmentManager = getSupportFragmentManager();
	fragmentManager
			.beginTransaction()
			.replace(R.id.container,
					PlaceholderFragment.newInstance(position + 1)).commit();
}

NavigationDrawerCallbacksを実装
アイテム選択時に対応する画面に遷移させる

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	Log.v("hangame", "onCreateOptionsMenu");
	
	if (!mNavigationDrawerFragment.isDrawerOpen()) {
		// Only show items in the action bar relevant to this screen
		// if the drawer is not showing. Otherwise, let the drawer
		// decide what to show in the action bar.
		getMenuInflater().inflate(R.menu.main, menu);
		restoreActionBar();
		return true;
	}
	return super.onCreateOptionsMenu(menu);
}

drawer側のfragmentにもmenuが設定されているために、drawerが開いている際にはactivityのmenuは表示されないようにする
※下の方のfragmentのソースにonPrepareOptionsMenuをcallして設定したいみたいなこと書いてあるけど、なぜかここに書いてある

public void restoreActionBar() {
	ActionBar actionBar = getSupportActionBar();
	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
	actionBar.setDisplayShowTitleEnabled(true);
	actionBar.setTitle(mTitle);
}

actionBarの初期化、NavigationBarを使用するように設定

fragment

/**
 * A pointer to the current callbacks instance (the Activity).
 */
private NavigationDrawerCallbacks mCallbacks;

/**
 * Helper component that ties the action bar to the navigation drawer.
 */
private ActionBarDrawerToggle mDrawerToggle;

private DrawerLayout mDrawerLayout;

mCallbacks:activityに設定するcallback
mDrawerToggle:NavigationBarへの設定を行う、開いたときや閉じたときのリスナーもここで管理する
mDrawerLayout:メイン画面

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

drawerが開いていたら復帰時に開いている状態になるように、sharedpreferencesに保存したものを酔いとる
これはandroidデザインパターンらしい
また、savedInstanceStateからdrawerのどこを選択していたか呼び出し、そこを選択状態にする

@Override
public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

fragmentのオプションメニューを有効に

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    mDrawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    });
    mDrawerListView.setAdapter(new ArrayAdapter<String>(
            getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_1,
            android.R.id.text1,
            new String[]{
                    getString(R.string.title_section1),
                    getString(R.string.title_section2),
                    getString(R.string.title_section3),
            }));
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

drawerのレイアウト取得してイベント、アダプターの設定

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId   The android:id of this fragment in its activity's layout.
 * @param drawerLayout The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

セットアップ処理1
必要なレイアウトを取得して、初期化処理など
eclipseでNavigationDrawerを作成すると「R.drawable.drawer_shadow」などのリソースを自動で設定してくれて便利

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(
            getActivity(),                    /* host Activity */
            mDrawerLayout,                    /* DrawerLayout object */
            R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
            R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
            R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }

            if (!mUserLearnedDrawer) {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

セットアップ処理2
ActionBarDrawerToggleの設定
パラメータについてはコメントの通り
if (!isAdded())はfragmentにviewが設定されているかの確認

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

セットアップ処理3
以前の状態を復元している処理がメイン
mDrawerToggle.syncState();で、drawerと画面の同期をとっている
、なんで別スレッドにしてるんだろ…以前の状態に依存するため遅らせてるってことは、前の状態を復帰させるのに必要なのかな

private void selectItem(int position) {
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
}

アイテム選択時の処理
activityに処理をわたしてる

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mCallbacks = (NavigationDrawerCallbacks) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

attach,detach処理

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

選択箇所保存、向き変更時にdrawerにイベント通知

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // If the drawer is open, show the global app actions in the action bar. See also
    // showGlobalContextActionBar, which controls the top-left area of the action bar.
    if (mDrawerLayout != null && isDrawerOpen()) {
        inflater.inflate(R.menu.global, menu);
        showGlobalContextActionBar();
    }
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    if (item.getItemId() == R.id.action_example) {
        Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

drawer用のmenuの設定

/**
 * Per the navigation drawer design guidelines, updates the action bar to show the global app
 * 'context', rather than just what's in the current screen.
 */
private void showGlobalContextActionBar() {
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setTitle(R.string.app_name);
}

private ActionBar getActionBar() {
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

actionBarの設定

/**
 * Callbacks interface that all activities using this fragment must implement.
 */
public static interface NavigationDrawerCallbacks {
    /**
     * Called when an item in the navigation drawer is selected.
     */
    void onNavigationDrawerItemSelected(int position);
}

activityで処理すべきinterface
アイテム選択時の処理

まとめ

  • NavigationDrawer部分をfragmentにしなければもうちょっとシンプルになると思うんだけど、多分fragmentで使うことの方が多いと思う
  • 実装部分もほかと比べて少しめんどくさいけど、anroidのデザインパターンの理解で時間がかかった
  • menuの制御とNavigationDrawerの制御をあわせてやっているので最初わかりにくかったけ、それをふまえて読めばわりと理解できた

参考
setHasOptionsMenu(true) を忘れるな!
技術見聞録 - ActionBar.Tabでandroid.R.id.contentに2つのListFragmentを入れた場合の対処
ActionBarDrawerToggle | Android Developers