在运行时单击时,我需要更改FloatingActionButton
的背景颜色。
我的代码:
public static void setButtonTint(FloatingActionButton button, ColorStateList tint) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
((TintableBackgroundView) button).setSupportBackgroundTintList(tint);
} else {
ViewCompat.setBackgroundTintList(button, tint);
}
}
public void switchFABmode(){
switch (floatingActionButtonMode){
case 0:
setButtonTint(shareFAB,getResources().getColorStateList(R.color.colorGrey));
setButtonTint(deleteFAB,getResources().getColorStateList(R.color.colorPrimary));
floatingActionButtonMode = 1;
Toast.makeText(this, "Tap time to delete",Toast.LENGTH_SHORT).show();
break;
case 1:
shareFAB.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
deleteFAB.setBackgroundColor(ContextCompat.getColor(this, R.color.colorGrey));
Toast.makeText(this,"Tap time to share", Toast.LENGTH_SHORT).show();
floatingActionButtonMode = 0;
break;
}
}
无法完成。有人可以指出我的错误,还是可以提供解决方案?
答案 0 :(得分:0)
答案 1 :(得分:0)
好吧,我将代码插入到我的测试项目中(几乎没有更改),并且一切正常。
FloatingActionButton fab;
int floatingActionButtonMode = 0;
public static void setButtonTint(FloatingActionButton button, ColorStateList tint) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
((TintableBackgroundView) button).setSupportBackgroundTintList(tint);
} else {
ViewCompat.setBackgroundTintList(button, tint);
}
}
public void switchFABmode(){
switch (floatingActionButtonMode){
case 0:
setButtonTint(fab,getResources().getColorStateList(R.color.colorPrimary));
floatingActionButtonMode = 1;
Toast.makeText(getActivity(), "Tap time to delete",Toast.LENGTH_SHORT).show();
break;
case 1:
setButtonTint(fab,getResources().getColorStateList(R.color.colorAccent));
Toast.makeText(getActivity(),"Tap time to share", Toast.LENGTH_SHORT).show();
floatingActionButtonMode = 0;
break;
}
}
和片段的onCreateView
中:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.map, container, false);
fab = v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchFABmode();
}
});
return v;
}