Use Custom View as Actionbar Icon

200 views Asked by At

I'm trying to use a custom view as the icon next to the up button. I searched for a solution online and read something about using a drawing cache and tried implementing it in my code but no icon is showing.

    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);

Thanks for any help :)

1

There are 1 answers

0
Rolf ツ On BEST ANSWER

Your code is probably not working because the view does not have a size yet. I also suggest you don't use the drawing cache but instead draw the view on a canvas.

I have written a little example where the view is given a size when it doesn't have one yet. You may want to tune to code a bit to fit your needs.

Example:

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);
}

Usage:

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:

result