FloatingActionButton с текстом вместо изображения
Я пытаюсь выяснить, как можно модифицировать FloatingActionButton из библиотеки поддержки Android. Может ли он использоваться с текстом вместо изображения?
Что-то вроде этого:
![введите описание изображения здесь]()
Я вижу, что он расширяет ImageButton, поэтому я не думаю. Я прав?
Правильно ли это в плане дизайна материалов?
Ответы
Ответ 1
С API 28 вы можете просто добавлять текст в Fabs используя:
Посетите: 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"/>
Ответ 2
Спасибо всем.
Вот простой способ, который я нашел для этого вопроса. Работает правильно для Android 4+, для Android 5+ добавлен специальный параметр android: возвышение для рисования TextView над 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>
Ответ 3
преобразовать текст в растровое изображение и использовать его. это супер легко.
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;
}
Ответ 4
FAB обычно используются в CoordinatorLayout
s. Вы можете использовать это:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:backgroundTint="@color/colorPrimary" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="OK"
android:elevation="6dp"
android:textSize="18dp"
android:textColor="#fff"
app:layout_anchor="@id/fab"
app:layout_anchorGravity="center"/>
</android.support.design.widget.CoordinatorLayout>
Вот что делает работа
app:layout_anchor="@id/fab"
app:layout_anchorGravity="center"
Результат:
![The Result]()
Если вы используете какой-то layout_behavior
для своего FAB, вам нужно сделать аналогичный layout_behavior
для TextView
Ответ 5
Вы не можете установить текст для FloatingActionButton
из библиотеки поддержки, но что вы можете сделать, это создать текстовое изображение непосредственно из студии android: File -> New -> Image Asset
, а затем использовать его для вашей кнопки.
В терминах Конструкция материалов; они не упоминают использование текста с FloatingActionButton
, и я не вижу причин для этого, поскольку у вас на самом деле нет места для текста.
Ответ 6
Мне нужен был текст в FAB, но вместо этого я просто выбрал TextView с круглым рисованным фоном:
<TextView
android:layout_margin="10dp"
android:layout_gravity="right"
android:gravity="center"
android:background="@drawable/circle_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textStyle="bold"
android:fontFamily="sans-serif"
android:text="AuthId"
android:textSize="15dp"
android:elevation="10dp"/>
Вот рисунок (circle_backgroung.xml):
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#666666"/>
<size
android:width="60dp"
android:height="60dp"/>
</shape>
![enter image description here]()
Ответ 7
Ответ @NandanKumarSingh fooobar.com/questions/125278/... работает, но я внес некоторые изменения в коде fab (не в xml, потому что они будут перезаписаны в методах класса)
fab.setTextBitmap("ANDROID", 100f, Color.WHITE)
fab.scaleType = ImageView.ScaleType.CENTER
fab.adjustViewBounds = false
Где setTextBitmap
- это расширение для класса ImageView
со схожей функциональностью, но оно поддерживает многоканальный текст
fun ImageView.setTextBitmap(text: String, textSize: Float, textColor: Int) {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.textSize = textSize
paint.color = textColor
paint.textAlign = Paint.Align.LEFT
val lines = text.split("\n")
var maxWidth = 0
for (line in lines) {
val width = paint.measureText(line).toInt()
if (width > maxWidth) {
maxWidth = width
}
}
val height = paint.descent() - paint.ascent()
val bitmap = Bitmap.createBitmap(maxWidth, height.toInt() * lines.size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
var y = - paint.ascent()
for (line in lines) {
canvas.drawText(line, 0f, y, paint)
y += height
}
setImageBitmap(bitmap)
}
Ответ 8
Очень небольшая модификация, чтобы товарищ ответил, что поддерживает API для Android ниже 21, просто добавьте app:elevation="0dp"
в FloatingActionButton
Это может помочь другим!