Zac*_*ach 8 android android-support-library floating-action-button
Programmatically setting my FloatingActionButton's backgroundTint via setBackgroundTintList method does not work, but setting it via XML app:backgroundTint tag does work - why is that?
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>
Run Code Online (Sandbox Code Playgroud)
我的活动布局是:
<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>
Run Code Online (Sandbox Code Playgroud)
和活动代码:
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果我添加:
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"
Run Code Online (Sandbox Code Playgroud)
对于 FloatingActionButton 的活动布局代码,我得到了预期的行为。
有什么想法吗?难道我做错了什么?
noe*_*noe 17
用这个:
fab.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.purple_200));
Run Code Online (Sandbox Code Playgroud)
干杯!
由于setBackgroundTintList仅在 API 21+ 中受支持,因此您可以使用 ViewCompat。
ViewCompat.setBackgroundTintList(
fab,
ContextCompat.getColorStateList(
getApplicationContext(),
R.color.purple_200
)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19900 次 |
| 最近记录: |