预备棒棒糖设备上的Android setBackgroundTintList

Mat*_*teo 17 android setbackground floating-action-button

我正在和我一起工作FloatingActionButton.用户应该能够在onClick事件中切换FAB背景颜色.

但是,建议的调用setBackgroundTintList似乎只能兼容21+ API.

我如何 - 正确 - 在棒棒糖前设备上进行操作?我可以使用任何替代方案吗?

提前致谢.

Ski*_*ᴉʞS 32

你也可以用 setSupportBackgroundTintList

对背景drawable应用色调.不修改当前的色调模式,默认情况下为SRC_IN.

对View.setBackground(Drawable)的后续调用将自动改变drawable并应用指定的色调和色调模式.

另外看一看 ViewCompat.setBackgroundTintList()

对背景drawable应用色调.

在API v21或更高版本上运行时,这将始终生效.在API v21之前的平台上运行时,只有在视图实现TintableBackgroundView接口时才会生效.

我在SO上找到了一个我以前用过的解决方案,是这样的:

public static void setButtonTint(Button button, ColorStateList tint) {
  if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && button instanceof AppCompatButton) {
      ((AppCompatButton) button).setSupportBackgroundTintList(tint);
  } else {
      ViewCompat.setBackgroundTintList(button, tint);
  }
}
Run Code Online (Sandbox Code Playgroud)

它适用于我,我希望它也适合你.

  • 我在使用AppCompatButton.setBackgroundTintList()时收到lint警告AppCompatButton.setSupportBackgroundTintList只能在同一个库组中调用(groupId = com.android.support) (2认同)

Rüd*_*ger 8

简单:

fab.setBackgroundTintList(ColorStateList.valueOf(0xFF4CAF50));
Run Code Online (Sandbox Code Playgroud)

fab是你FloatingActionButton的当然,0xFF4CAF50只是一个例子的颜色