Android工具栏主页/向上指示器未读计数

时间:2016-02-18 19:48:48

标签: android toolbar

我有一个主/详细视图,我需要在“up / home / back”按钮中添加未读数。我使用app:actionlayout将未读计数添加到其他工具栏项目中,但在这种情况下我没有看到它有用。

我相信我需要获得对home / up菜单项的引用,并添加一个视图。如果是这种情况,我需要获得对菜单项的引用,这是我迄今为止不成功的事情。还有另外一种技术吗?

1 个答案:

答案 0 :(得分:3)

请尝试我的实施,看起来像notification with counter example

细节代码片段:

      final Toolbar toolbar = (Toolbar) activity.findViewById(R.id.detail_toolbar);
        if (toolbar != null) {
            final Drawable icon = toolbar.getNavigationIcon();
            if (icon != null) {
                if (icon instanceof BitmapDrawable) {
                    final BitmapDrawable bitmapDrw = (BitmapDrawable) icon;
                    final OverlayDrawable overlay = new OverlayDrawable(getResources(), bitmapDrw.getBitmap());
                    toolbar.setNavigationIcon(overlay);
                    overlay.setCount(1);
                }
            }
        }

可绘制代码:

public class OverlayDrawable extends BitmapDrawable {

private final Paint mPaintCircle;
private final Paint mPaintText;

private int mCount = 0;
private final Rect mTextBounds;

public OverlayDrawable(Resources res, Bitmap bitmap) {
    super(res, bitmap);

    mPaintCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaintCircle.setColor(Color.RED);

    mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaintText.setColor(Color.WHITE);

    mTextBounds = new Rect();

}

public void setCount(int count) {
    mCount = count;
}

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);

    float minSize = Math.min(getIntrinsicWidth(), getIntrinsicHeight());
    float radius = minSize / 3.0f;
    float x = getIntrinsicWidth() - radius / 2;
    float y = minSize / 4.0f;
    mPaintText.setTextSize(1.5f * radius);
    canvas.drawCircle(x, y, radius, mPaintCircle);

    final String text = Integer.toString(mCount);
    mPaintText.getTextBounds(text, 0, text.length(), mTextBounds);

    canvas.drawText(text, x - mTextBounds.width() / 2.0f - mTextBounds.left - 1, y + mTextBounds.height() / 2.0f, mPaintText);
}

}