在运行时更改FloatingActionButton背景颜色

时间:2018-10-02 18:36:42

标签: java android floating-action-button

在运行时单击时,我需要更改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;
        }
}

无法完成。有人可以指出我的错误,还是可以提供解决方案?

2 个答案:

答案 0 :(得分:0)

使用此:

button.setBackgroundColor(ContextCompat.getColor(this, R.color.colorGrey));

来自here的更多内容

答案 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;
}