如何在Android操作栏中获取标签 [英] How to get a label in the Android action bar

查看:178
本文介绍了如何在Android操作栏中获取标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想在操作栏中添加一些文本.首先,这是我在想像的一个样机(在Paint中!):

As the title suggests, I want to put some text in the action bar. Firstly, here's a mockup (in Paint!) of what I'm imagining:

我真的为此感到挣扎.在我的活动中,我输入:

I'm really struggling with this. In my activity I put:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main_screen, menu);
  return true;
}

然后在菜单文件夹中放入main_screen.xml:

And in the menu folder I put main_screen.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

  <item android:id="@+id/user_level"
    android:title="Administrator"
    android:showAsAction="withText" />

</menu>

所以我有2个问题:

为什么至少上面的解决方案没有显示文本Administrator

Why at the very least the solution above doesn't show the text Administrator

一旦显示了文本,如何使它看起来像标签(带有灰色背景和圆角等)?

Once it's showing the text, how do I make it appear like a label (with the grey background and the rounded corners, etc)?

谢谢您的帮助.

推荐答案

自定义菜单项是您第二个问题所需要的.

custom menu item is what you need for your second question.

首先,您需要为菜单项进行自定义布局.

first you need to make custom layout for your menu item.

cust_menu.xml

<TextView
    android:id="@+id/admin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:text="Administrator"
    android:textColor="#fff"
    android:background="@drawable/my_shape";
    android:textStyle="bold" />

要制作圆形的灰色正方形背景,您需要制作自定义形状文件并将其设置为您的TextView背景.

for making rounded grey square background you need to make custom shape file and set it to your TextView background.

my_shape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="3dp" />

    <solid android:color="#e3e3e3" />

</shape>

现在您的菜单项将变成这样.

now your menu item will go like this.

main.xml

<item
    android:id="@+id/admin"
    android:actionLayout="@layout/cust_menu"
    app:showAsAction="always">
</item>

在Java类中只需执行此操作即可.

and in java class simply do this.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

让我知道是否有任何疑问.

let me know if any doubts.

有关更多信息,请访问

for more information visit this

您可以通过这种方式访问​​TextView.

you can access your TextView this way.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.main, menu);

    View view = menu.findItem(R.id.admin).getActionView();
    TextView textView = (TextView) view.findViewById(R.id.textID);

    // do your stuff

    return super.onCreateOptionsMenu(menu);
}

快乐的编码.

这篇关于如何在Android操作栏中获取标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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