Can I display text / number on FloatingActionButton (Fab)? I have a news feed and I want to conclude page numbering. Can I be on top of the fab tex with reference to it?

  • this can not be done ( - iFr0z

1 answer 1

Create a class TextDrawable.java and use for your purposes:

 fab.setImageDrawable(new TextDrawable("2", ColorStateList.valueOf(Color.BLACK), 32.f, TextDrawable.VerticalAlignment.BASELINE)); 

TextDrawable :

 public class TextDrawable extends Drawable { protected final Paint textPaint; protected ColorStateList color; protected String text; protected int iHeight; protected int iWidth; protected int measuredWidth, measuredHeight; private float ascent; private VerticalAlignment verticalAlignment; public TextDrawable(String text, ColorStateList color, float textSize, VerticalAlignment verticalAlignment) { textPaint = new Paint(); this.text = text; initPaint(); this.textPaint.setTextSize(textSize); measureSize(); setBounds(0, 0, iWidth, iHeight); this.color = color; textPaint.setColor(color.getDefaultColor()); this.verticalAlignment = verticalAlignment; } private void initPaint() { textPaint.setAntiAlias(true); textPaint.setTextAlign(Paint.Align.CENTER); } public void setColor(ColorStateList colorStateList) { if (this.color == null || !this.color.equals(colorStateList)) { this.color = colorStateList; invalidateSelf(); } } protected void measureSize() { ascent = -textPaint.ascent(); iWidth = (int) (0.5f + textPaint.measureText(text)); iHeight = (int) (0.5f + textPaint.descent() + ascent); measuredWidth = iWidth; measuredHeight = iHeight; } @Override public void draw(Canvas canvas) { if (text == null || text.isEmpty()) { return; } final Rect bounds = getBounds(); int stack = canvas.save(); canvas.translate(bounds.left, bounds.top); if (text != null && !text.isEmpty()) { final float x = bounds.width() >= iWidth ? bounds.centerX() : iWidth * 0.5f; float y = 0; switch (verticalAlignment) { case BASELINE: y = (bounds.height() - iHeight) * 0.5f + ascent; break; case TOP: y = bounds.height(); break; case BOTTOM: y = bounds.height(); break; } canvas.drawText(text, x, y, textPaint); } canvas.restoreToCount(stack); } @Override public void setAlpha(int alpha) { if (textPaint.getAlpha() != alpha) { textPaint.setAlpha(alpha); invalidateSelf(); } } @Override public void setColorFilter(ColorFilter cf) { if (textPaint.getColorFilter() == null || !textPaint.getColorFilter().equals(cf)) { textPaint.setColorFilter(cf); invalidateSelf(); } } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } public enum VerticalAlignment { TOP, BOTTOM, BASELINE } } 

result: enter image description here

  • thank you so much - Artem