如何在选中时使SwitchCompat不改变颜色?

时间:2015-03-29 15:51:09

标签: android colors android-styles tint switchcompat

这就是未经检查的样子:

pic

并检查:

pic

显然检查不匹配设计,那么在检查设计时如何让它看起来像未经检查?

2 个答案:

答案 0 :(得分:1)

您可以为两种语句使用相同的颜色着色:

    switchButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            isTouched = true;
            switchButton.getThumbDrawable().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_IN);
            return false;
        }
    });
    switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if (isTouched) {
                isTouched = false;
                if (isChecked) {
                    switchButton.getThumbDrawable().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_IN);
                }
                else {
                    switchButton.getThumbDrawable().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_IN);
                }
            }
        }
    });

答案 1 :(得分:1)

知道了!我不得不做一些研究,android如何找到更暗的颜色...

switchview.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            switchview.getThumbDrawable().clearColorFilter();
            int colorPrimaryDark = getResources().getColor(R.color.colorPrimaryDark);
            int r = (colorPrimaryDark >> 16) & 0xFF;
            int g = (colorPrimaryDark >> 8) & 0xFF;
            int b = (colorPrimaryDark >> 0) & 0xFF;
            r = (r - 30 < 0) ? 0 : r - 30;
            g = (g - 30 < 0) ? 0 : g - 30;
            b = (b - 30 < 0) ? 0 : b - 30;
            int darker = Color.rgb(r, g, b);
            switchview.getTrackDrawable().setColorFilter(darker, PorterDuff.Mode.SRC_IN);
        }
    });

现在选中并取消选中将完全相同。