通过使用XML中的app:backgroundTint
标签来设置FloatingActionButton
的backgroundTint
属性是有效的,但是通过使用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 的活动布局代码,我得到了预期的行为。
有什么想法吗?我做错了什么吗?
onClickListener()
内添加setBackgroundTintList()
来简化它吗? - OBX