首页 > 系统 > Android > 正文

[Android]添加菜单栏

2019-11-09 13:56:05
字体:
来源:转载
供稿:网友

添加菜单栏

–根据Udacity中ud851课程整理笔记

创建menu资源文件:

// 在res中新建menu的文件夹并创建 menu.xml // 给菜单栏添加一个item, 其中orderInCategory(int)为摆放顺序 <item android:title="@string/search" android:id="@+id/action_search" android:orderInCategory="1" app:showAsAction="ifRoom" />

在MainActivity中重写:

// DONE (8) Override onCreateOptionsMenu // DONE (9) Within onCreateOptionsMenu, use getMenuInflater().inflate to inflate the menu // DONE (10) Return true to display your menu @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } // DONE (11) Override onOptionsItemSelected // DONE (12) Within onOptionsItemSelected, get the ID of the item that was selected // DONE (13) If the item's ID is R.id.action_search, show a Toast and return true to tell Android that you've handled this menu click // DONE (14) Don't forgot to call .show() on your Toast // DONE (15) If you do NOT handle the menu click, return super.onOptionsItemSelected to let Android handle the menu click @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.action_search){ Toast.makeText(this,"search clicked",Toast.LENGTH_LONG).show(); } return super.onOptionsItemSelected(item); }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表