FloatingActionButton with text instead of image
Solution 1:
Thanks to all.
Here is easy workaround which I found for this question. Works correctly for Android 4+, for Android 5+ is added specific parameter android:elevation to draw TextView over FloatingActionButton.
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:color/transparent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@android:string/ok"
android:elevation="16dp"
android:textColor="@android:color/white"
android:textAppearance="?android:attr/textAppearanceMedium" />
</FrameLayout>
Solution 2:
convert a text into bitmap and use it. its super easy.
fab.setImageBitmap(textAsBitmap("OK", 40, Color.WHITE));
//method to convert your text to image
public static Bitmap textAsBitmap(String text, float textSize, int textColor) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(textSize);
paint.setColor(textColor);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = -paint.ascent(); // ascent() is negative
int width = (int) (paint.measureText(text) + 0.0f); // round
int height = (int) (baseline + paint.descent() + 0.0f);
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawText(text, 0, baseline, paint);
return image;
}
Solution 3:
With API 28 you can simply add text to Fabs using:
Visit: https://material.io/develop/android/components/extended-floating-action-button/
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:contentDescription="@string/extended_fab_content_desc"
android:text="@string/extended_fab_label"
app:icon="@drawable/ic_plus_24px"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="bottom|right|end"/>