如何以编程方式使用 ColorStateList 设置 FloatingActionButton 的 backgroundTint?

新手上路,请多包涵

Programmatically setting my FloatingActionButton ’s backgroundTint via setBackgroundTintList method does not work, but setting it via XML app:backgroundTint tag does work - why is那?

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 的活动布局代码,我得到了预期的行为。

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

原文由 Zach 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 384
2 个回答

自 Android 支持库 25.1.0 起,此问题已得到解决

请参阅: https ://code.google.com/p/android/issues/detail?id=227428

原文由 Zach 发布,翻译遵循 CC BY-SA 3.0 许可协议

用这个:

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

原文由 noe 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题