ActionBarSherlock中的自定义菜单项

时间:2013-05-29 15:10:01

标签: android actionbarsherlock

我需要在ActionBar中有一个自定义菜单项,它只显示一些自定义格式的文本。所以我想我会动态创建一个图像并将其附加到菜单图标上。所以在我的代码中,我认为我可以使用Layout xml来编写我的文本:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content">
    <TextView android:textColor="#bcbcbb"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:text="Some Text"/>
    <TextView android:textColor="#ffffff"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/replace_text" android:text="XXXX"/>
</LinearLayout>

然后创建一个绘制到DrawableBitmap的临时布局:

        LinearLayout layout = (LinearLayout)View.inflate(getApplicationContext(), R.layout.refund_text, null );
        layout.setDrawingCacheEnabled(true);
        layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        layout.layout(0, 0, mRefundLayout.getWidth(), layout.getHeight());
        layout.buildDrawingCache(true);
        Bitmap bitmap = Bitmap.createBitmap(layout.getDrawingCache());
        BitmapDrawable bm = new BitmapDrawable( getBaseContext().getResources(), bitmap);
        layout.setDrawingCacheEnabled(false);
....do something with the bitmap

然而,在测量调用宽度和高度仍然为零之后。谁能告诉我我做错了什么?

此致 利

1 个答案:

答案 0 :(得分:0)

如果你只想控制MenuItem中文本的颜色,你可以简单地通过格式化(使用SpannableStringBuilder)传递给MenuItem.add的charSequence(int groupId,int itemId,int order, CharSequence标题)。我没试过,让我们知道它是否有效!

如果你最后想要做更多的事情,那么创建你自己的自定义ActionProvider,在onCreateActionView()中膨胀你的布局,在onPerformDefaultAction()中“做一些东西”。