7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FragmentでのActionBarの実装メモ【Android】

Last updated at Posted at 2018-04-23

Fragment#onCreateView

Fragment#onCreateView
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.search_history, container, false);
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.searchHIstoryToolbar);

// 1.activityを取得する。
    activity = (AppCompatActivity) getActivity(); 
// 2.ActionBarを設置する。
    activity.setSupportActionBar(toolbar);
// 3.ActionBarにhomeボタンを表示する。
    activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);     
// 4.3で設定したhomeボタンを押下できる設定にする。
    activity.getSupportActionBar().setHomeButtonEnabled(true);
// 5.Fragment#onOptionsItemSelectedを有効にする。
    setHasOptionsMenu(true);

    recyclerView = (RecyclerView) view.findViewById(R.id.search_history_list);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    return view;
}

Fragment#onOptionsItemSelected

Fragment#onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            getFragmentManager().popBackStack();
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

ハマったこと

はじめActionBarに表示されたhomeボタンをタッチしても、onOptionsItemSelected関数が反応しませんでした。

Fragment#onCreateViewの「5.Fragment#onOptionsItemSelectedを有効にする」を加えることで反応するようになりました。

以下の説明にもある通り、このメソッドにtrueを渡して実行することで、onCreateOptionsMenu及びonOptionsItemSelectedなどの関連メソッドの実行をFragmentが受信するようになるみたいです。

    /**
     * Report that this fragment would like to participate in populating
     * the options menu by receiving a call to {@link #onCreateOptionsMenu}
     * and related methods.
     *
     * @param hasMenu If true, the fragment has menu items to contribute.
     */
    public void setHasOptionsMenu(boolean hasMenu) {
        if (mHasMenu != hasMenu) {
            mHasMenu = hasMenu;
            if (isAdded() && !isHidden()) {
                mHost.onSupportInvalidateOptionsMenu();
            }
        }
    }
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?