【发布时间】:2015-07-13 15:08:30
【问题描述】:
有没有办法可以在ActionBar 的右上角添加一个按钮,例如默认设置Button 的位置?我删除了设置Button,但我想在其位置添加自定义Button。
【问题讨论】:
标签: android android-actionbar android-button
有没有办法可以在ActionBar 的右上角添加一个按钮,例如默认设置Button 的位置?我删除了设置Button,但我想在其位置添加自定义Button。
【问题讨论】:
标签: android android-actionbar android-button
您可以通过编辑/创建菜单 xml 文件来添加按钮:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_name"
android:icon="@drawable/you_resource_here"
android:title="Text to be seen by user"
app:showAsAction="always"
android:orderInCategory="0"/>
</menu>
然后在您的活动中,如果您创建了一个新文件,您需要编辑onCreateOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
您可以通过以下方法编辑操作的作用:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_name) {
return true;
}
return super.onOptionsItemSelected(item);
}
【讨论】:
这可能更容易,但我使用工具栏代替:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_name:
//your code
break;
}
return super.onOptionsItemSelected(item);
}
【讨论】: