在项目菜单操作栏上绘制文本

时间:2015-01-09 03:59:16

标签: android android-canvas

我想在操作栏中的项目图标上绘制文字。我当前的操作栏是这样的:

enter image description here

我希望是这样的:

enter image description here

我试过这段代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    getMenuInflater().inflate(R.menu.main, menu);
    shoppingCardTopMenu = menu.findItem(R.id.top_menu_shopping_card);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(30, 30, conf);

    Paint paint = new Paint();
    Canvas canvas = new Canvas(bmp);
    canvas.drawPaint(paint);
    paint.setColor(Color.BLACK);
    paint.setTextSize(16);
    canvas.drawText("test", 0, 0, paint);

    shoppingCardTopMenu.getIcon().draw(canvas);

    return true;
}

但没有工作。有什么解决方案吗?

1 个答案:

答案 0 :(得分:1)

我不知道它会不会对您有用但是请尝试这种方式,因为我有按钮,添加自定义项目..

  <item
    android:id="@+id/badge"
    android:actionLayout="@layout/feed_update_count"
    android:icon="@drawable/shape_notification"
    android:showAsAction="always">
 </item>

按钮

     <Button xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/notif_count"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:minWidth="32dp"
      android:minHeight="32dp"
      android:background="@drawable/yourthings"
      android:text="0"
      android:textSize="16sp"
      android:textColor="@android:color/white"
      android:gravity="center"
      android:padding="2dp"
      android:singleLine="true">    
     </Button>

Youractivity

static Button notifCount;
static int mNotifCount = 0;    

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

View count = menu.findItem(R.id.badge).getActionView();
notifCount = (Button) count.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
return super.onCreateOptionsMenu(menu);
}

private void setNotifCount(int count){
mNotifCount = count;
invalidateOptionsMenu();
}