48

Я пытаюсь выяснить, как можно модифицировать FloatingActionButton из библиотеки поддержки android. Может ли он использоваться с текстом вместо изображения?FloatingActionButton с текстом вместо изображения

Что-то вроде этого:

enter image description here

Я вижу это расширяет ImageButton, так что я думаю, что нет. Я прав?

Правильно ли это с точки зрения дизайна материалов?

+0

Да, вы не можете. –

ответ

70

Спасибо всем.

Это проворное решение, которое я нашел для этого вопроса. Работает правильно для 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> 
+0

awesome, спасибо! –

+0

моложе сделано: D. Благодаря! –

+1

TextView, показывающий тень из-за свойств высоты, –

11

Вы не можете установить текст для FloatingActionButton из библиотеки поддержки, но что вы можете сделать, это создать текстовое изображение непосредственно из студии android: File -> New -> Image Asset, а затем использовать его для вашей кнопки.

Сроки Материальный дизайн; они не упоминали использование текста с FloatingActionButton, и я не вижу причин для этого, поскольку у вас на самом деле нет места для текста.

+3

Текст, подобный «OK», «YES», «NO», «GO» идеально вписывается в FAB .......... – MarsAndBack

32

конвертировать текст в растровое изображение и использовать его. его очень легко.

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; 
} 
+0

Идеально, но размер текста не меняется. –

+0

@ Ankur_009 его изменения. Попытайтесь увеличить значение на довольно большой размер, как в поплавке. – pratz9999

+0

сладкий, с небольшими изменениями Я заставил его работать, чтобы преобразовать шрифты значков в чертежи – SolidSnake

12

FAB обычно используются в CoordinatorLayout. Вы можете использовать это:

<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

+1

Получение ошибки android.support.design.widget.FloatingActionButton нельзя отнести в android.view.ViewGroup –

+1

Вы уверены, что ваш FloatingActionButton находится внутри CoordinatorLayout? – lokeshrmitra

+0

Да @lokeshmitra –

1

Я нуждаясь текстом в 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