以編程方式設置我的FloatingActionButton
的backgroundTint
通過setBackgroundTintList
方法不起作用,但通過XML設置app:backgroundTint
標記確實有效 - 爲什麼?如何用ColorStateList以編程方式設置FloatingActionButton的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活動佈局代碼,我得到預期的行爲。
有什麼想法?難道我做錯了什麼?
什麼時候的程序化方法不起作用?在點擊狀態? – OBX
當按鈕被設置爲選擇(在我的活動代碼中完成)時,顏色不會更新。它保持默認的顏色。 – Zach
要選擇的設置?你在'onClickListener()'裏面加入'setBackgroundTintList()'來簡化它嗎? – OBX