如何通过ColorStateList编程设置FloatingActionButton的背景色?

14

通过使用XML中的app:backgroundTint标签来设置FloatingActionButtonbackgroundTint属性是有效的,但是通过使用setBackgroundTintList方法在程序中设置该属性无效 - 为什么会这样呢?

fab_background_color.xml颜色列表状态如下:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true"
          android:color="#654321"/>

    <item android:color="#123456"/>

</selector>

我的活动布局是:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</android.support.design.widget.CoordinatorLayout>

以及活动代码:

public class SampleActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_position_sample);

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.test);

        // Uncomment to test - this does NOT work however.
        //fab.setBackgroundTintList(getResources().getColorStateList(R.color.fab_background_color));

        fab.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                if (fab.isSelected())
                    fab.setSelected(false);
                else
                    fab.setSelected(true);
            }
        });
    }
}

如果在设置点击监听器之前,向活动代码中添加以下内容:

fab.setBackgroundTintList(getResources().getColorStateList(R.color.fab_background_color));

或者:

fab.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.fab_background_color));

什么都不会发生。

如果在设置点击监听器之前添加上述代码,请按要求检查代码是否正确,以确保该代码是否会影响预期的行为。

app:backgroundTint="@color/fab_background_color"

对于 FloatingActionButton 的活动布局代码,我得到了预期的行为。

有什么想法吗?我做错了什么吗?


编程方法什么时候不起作用?在点击状态下吗? - OBX
当按钮被设置为选中状态(在我的活动代码中完成),颜色不会更新。它仍然保持默认颜色。 - Zach
要被选中吗?你是在onClickListener()内添加setBackgroundTintList()来简化它吗? - OBX
看看我的代码 - 我正在设置FAB被选中(如果它还没有被选中)。ColorStateList应该自动处理选择正确的颜色,这就是Color状态的全部意义。当然,我可以单独完成这个任务,但这不是重点 - 它应该基于视图的选定状态工作,但只有在通过XML设置时才能实现。 - Zach
将此作为Android问题编写:https://code.google.com/p/android/issues/detail?id=227428 - Zach
3个回答

26

使用这个:

fab.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.purple_200));

很遗憾,我没有看到任何行为上的区别。非常感谢。 - Zach
1
需要API 21+。 - Nathan F.

6

由于setBackgroundTintList仅支持API 21+,因此您可以使用ViewCompat。

ViewCompat.setBackgroundTintList(
    fab, 
    ContextCompat.getColorStateList(
        getApplicationContext(),
        R.color.purple_200
    )
);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接