如何在 ActionBar(Android) 中添加按钮? [英] How to add button in ActionBar(Android)?

查看:68
本文介绍了如何在 ActionBar(Android) 中添加按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在示例右侧的操作栏中添加一个按钮,如下面的屏幕截图所示:

I want to add a Button to the Action Bar to the right hand side of Example as in this screen shot:

我在 onCreate 方法中得到 actionBar 为:

I get actionBar in onCreate method as:

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

和后退按钮(onOptionsItemSelected 方法)如下:

and back button(onOptionsItemSelected method) as below:

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(),MainActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

如何添加按钮?

推荐答案

您必须在 res/menu 中创建一个条目,覆盖 onCreateOptionsMenu 并对其进行扩充

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

菜单条目可以是:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

这篇关于如何在 ActionBar(Android) 中添加按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆