【发布时间】:2016-11-04 15:53:56
【问题描述】:
通过setBackgroundTintList 方法以编程方式设置我的FloatingActionButton 的backgroundTint 不起作用,但通过XML app:backgroundTint 标记设置它确实有效 - 为什么会这样?
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 的活动布局代码,我得到了预期的行为。
有什么想法吗?我做错了吗?
【问题讨论】:
-
编程方法什么时候不起作用?处于点击状态?
-
当按钮设置为选中时(在我的活动代码中完成),颜色不会更新。它保持默认颜色。
-
设置为选中?为了简单起见,您是在
onClickListener()中添加setBackgroundTintList()吗? -
查看我的代码 - 我正在设置要选择的 FAB(如果尚未选择)。 ColorStateList 应该自动处理选择正确的颜色,这就是 Color 状态的重点。当然,我可以单独执行此操作,但这不是重点——它应该根据视图的选定状态工作,但只有在通过 XML 设置时才会这样做。
-
将此写为 Android 问题:code.google.com/p/android/issues/detail?id=227428
标签: android android-support-library floating-action-button