【问题标题】:FAB Change color of icon drawableFAB 更改可绘制图标的颜色
【发布时间】:2018-01-02 12:29:29
【问题描述】:

我在布局文件中将我的 FAB 定义为:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/search"
        app:rippleColor="@color/primary"
        app:elevation="1dp"
        app:borderWidth="4dp" />

这里的@drawable/search 是我从Android Studio 的Vector Asset 工具(Asset Type Material Icon)创建的一个文件。它被创建为黑色。如何更改 FAB 定义中使用的图标颜色?

【问题讨论】:

    标签: android floating-action-button


    【解决方案1】:

    使用android:tint 属性可以像这样设置颜色

    <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:tint="@android:color/white"
        android:src="@android:drawable/ic_input_add"/>
    

    您可以使用ColorFilter. 以编程方式更改它

    //get the drawable
    Drawable myFabSrc = getResources().getDrawable(android.R.drawable.ic_input_add);
    
    //copy it in a new one
    Drawable willBeWhite = myFabSrc.getConstantState().newDrawable();
    
    //set the color filter, you can use also Mode.SRC_ATOP
    willBeWhite.mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
    
    //set it to your fab button initialized before
    myFabName.setImageDrawable(willBeWhite);
    

    【讨论】:

      【解决方案2】:

      简单地说,要更改drawable 的颜色,找到res/drawable 文件夹并打开您想要的drawable 代码,

      <vector xmlns:android="http://schemas.android.com/apk/res/android"
              android:width="26dp"
              android:height="26dp"
              android:viewportWidth="24.0"
              android:viewportHeight="24.0">
          <path
              android:fillColor="#FFFFFF" <!-- change color here -->
              android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
      </vector>
      

      在这里,您可以使用android:fillColor 属性更改drawable 的颜色。

      编辑 -- 或者如果您想更改 fab xml 中可绘制图标的颜色,那么您可以在 fab 中使用 android:tint 作为,

      <android.support.design.widget.FloatingActionButton
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:tint="#FFFFFF"          <!-- your color here -->
          app:src="@drawable/ic_search" /> 
      

      【讨论】:

      • 我没有办法在 FAB XML 代码中做到这一点吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多