使用自定义视图作为操作栏图标

时间:2014-11-18 08:29:31

标签: android android-actionbar actionbarsherlock

我正在尝试使用自定义视图作为向上按钮旁边的图标。我在网上搜索了一个解决方案并阅读了一些关于使用绘图缓存的内容,并尝试在我的代码中实现它,但没有显示图标。

    ActionBar bar = getSupportActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.scheme_dark_blue)));
    bar.setTitle(i.getStringExtra("schoolDay"));
    CalendarIcon icon = (CalendarIcon) getLayoutInflater().inflate(R.layout.icon_calendar, null);
    icon.setDrawingCacheEnabled(true);
    day = Integer.parseInt(i.getStringExtra("date"));
    icon.setData(day + "");
    icon.buildDrawingCache();
    bar.setIcon(new BitmapDrawable(getResources(), icon.getDrawingCache()));
    bar.setDisplayHomeAsUpEnabled(true);

感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

您的代码可能无法正常工作,因为视图还没有大小。我还建议您不要使用绘图缓存,而是在画布上绘制视图。

我写了一个小例子,当视图没有时,会给出一个大小。您可能希望调整一下代码以满足您的需求。

示例:

public static Drawable createDrawableFromView(View v, int requestedWidth, int requestedHeight) {
    // Because the view is never shown it does not have a size, but if shown don't resize it.
    if (v.getMeasuredHeight() <= 0) {

        // You may want to change these lines according to the behavior you need.
        int specWidth = MeasureSpec.makeMeasureSpec(requestedWidth, MeasureSpec.AT_MOST);
        int specHeight = MeasureSpec.makeMeasureSpec(requestedHeight, MeasureSpec.AT_MOST);
        v.measure(specWidth, specHeight);
    }
    Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    v.draw(c);
    return new BitmapDrawable(v.getContext().getResources(), b);
}

<强>用法:

getActionBar().setTitle("View to icon test");
TextView view = new TextView(this);
view.setText("AI");
view.setGravity(Gravity.CENTER);
view.setTextColor(Color.RED);
getActionBar().setIcon(createDrawableFromView(view, 250, 250));

<强>结果:

result