根据共享偏好值android设置开关按钮状态

时间:2018-04-25 06:00:46

标签: android

我有一个自定义开关按钮用于出勤目的。我正在保存共享偏好的值。这些值正在被很好地检索,但是开关按钮的状态需要根据值创建时更改共享首选项。例如,如果值为true,则按钮将处于未选中状态,如果false按钮将处于检查状态,则实现此目的?

 getPreference();

    if(Common.punchedIn) {
       // switchButton.setOnCheckedChangeListener(null);
        switchButton.setChecked(false);
    }
    else
    {
       // switchButton.setOnCheckedChangeListener(null);
        switchButton.setChecked(true);
    }



switchButton.setOnCheckedChangeListener(new MySwitchButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(MySwitchButton s, boolean isChecked) {
    if(switchButton.isChecked()){
        String acTime = getActionTime();
        String acDate = getActionDate();
        String loc = getGPSLocation();
        String empID = getEmployeeID();
        String empReportingTo = getReportingTo();
        //Toast.makeText(AttendanceActivity.this, "Switch is currently ON", Toast.LENGTH_LONG).show();
        punchStatus_text.setText("Punch Out");
        shift_dur_text.setVisibility(View.INVISIBLE);
        shift_dur_time.setVisibility(View.INVISIBLE);
        checkin_time.setVisibility(View.VISIBLE);
        checkin_time.setText("Check in :"+acTime);
        checkout_time.setVisibility(View.INVISIBLE);
        saveAttendance(empID,empReportingTo,acDate,acTime,loc,"na","na","IN");
    }else{
        String acTime = getActionTime();
        String acDate = getActionDate();
        String loc = getGPSLocation();
        String empID = getEmployeeID();
        String empReportingTo = getReportingTo();
        //Toast.makeText(AttendanceActivity.this, "Switch is currently OFF", Toast.LENGTH_LONG).show();
        punchStatus_text.setText("Punch In");
        shift_dur_text.setVisibility(View.VISIBLE);
        shift_dur_time.setVisibility(View.VISIBLE);
        checkin_time.setText("Check in :"+Common.punchInTime);
        checkin_time.setVisibility(View.INVISIBLE);
        checkout_time.setVisibility(View.VISIBLE);
        checkout_time.setText("Check Out:"+acTime);
        saveAttendance(empID,empReportingTo,acDate,acTime,loc,"na","na","OUT");
    }
}

});

保存并从共享偏好中检索

public static boolean setPreference(Context context,boolean value) {
    SharedPreferences settings = context.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("punch",value);


    return editor.commit();
}

public void getPreference() {
    SharedPreferences settings = this.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    //  Toast.makeText(this,"EMP ID is "+emp_id,Toast.LENGTH_LONG).show();
    Common.punchedIn = settings.getBoolean("punch", false);
    Toast.makeText(this,"PUNCH IN STATUS "+String.valueOf(Common.punchedIn),Toast.LENGTH_LONG).show();
}

SWITCH BUTTON CLASS

public class MySwitchButton extends View implements Checkable {
private static final int ANIMATION_DURATION = 300;

private static final int DEFAULT_WIDTH = 100;
private static final int DEFAULT_HEIGHT = 50;
private static final int DEFAULT_SPOT_PADDING = 6;
private static final int DEFAULT_BORDER_WIDTH = 4;

private static final int DEFAULT_SWITCH_ON_COLOR = Color.LTGRAY;
private static final int DEFAULT_SWITCH_ON_COLOR_OUT = Color.LTGRAY;
private static final int DEFAULT_SWITCH_OFF_COLOR = Color.LTGRAY;
private static final int DEFAULT_SWITCH_OFF_COLOR_OUT = Color.LTGRAY;
private static final int DEFAULT_SPOT_ON_COLOR = R.color.colorBrown;
private static final int DEFAULT_SPOT_ON_COLOR_IN = R.color.colorBrown;
private static final int DEFAULT_SPOT_OFF_COLOR = R.color.colorBrown;
private static final int DEFAULT_SPOT_OFF_COLOR_IN = R.color.colorBrown;

private static final int SWITCH_OFF_POS = 0;
private static final int SWITCH_ON_POS = 1;

private int switchOnColor;
private int switchOffColor;
private int spotOnColor;
private int spotOnColorIn;
private int spotOffColor;
private int spotOffColorIn;
private int switchOnStrokeColor;
private int switchOffStrokeColor;
private int spotPadding;
private float currentPos;
private boolean mChecked;
private boolean mBroadcasting;
private boolean isMoving;
private int duration;

private OnCheckedChangeListener onCheckedChangeListener;

private ValueAnimator valueAnimator;

private enum State {
    SWITCH_ANIMATION_OFF, SWITCH_ANIMATION_ON, SWITCH_ON, SWITCH_OFF
}

private State state;

public MySwitchButton(Context context) {
    super(context);
    switchOnColor = DEFAULT_SWITCH_ON_COLOR;
    switchOffColor = DEFAULT_SWITCH_OFF_COLOR;
    spotOnColor = DEFAULT_SPOT_ON_COLOR;
    spotOnColorIn = DEFAULT_SPOT_ON_COLOR_IN;
    spotOffColor = DEFAULT_SPOT_OFF_COLOR;
    spotOffColorIn = DEFAULT_SPOT_OFF_COLOR_IN;
    spotPadding = dp2px(DEFAULT_SPOT_PADDING);
    switchOnStrokeColor = switchOnColor;
    switchOffStrokeColor = switchOffColor;
    duration = ANIMATION_DURATION;
    state = mChecked ? State.SWITCH_ON : State.SWITCH_OFF;

    setClickable(true);
}

public MySwitchButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Switch);
    switchOnColor = a.getColor(R.styleable.Switch_switchOnColor, DEFAULT_SWITCH_ON_COLOR);
    switchOffColor = a.getColor(R.styleable.Switch_switchOffColor, DEFAULT_SWITCH_OFF_COLOR);
   // switchOnColor = getResources().getColor(R.color.colorBrown);
    //switchOffColor = getResources().getColor(R.color.colorBrown);
    spotOnColor = a.getColor(R.styleable.Switch_spotOnColor, DEFAULT_SPOT_ON_COLOR);
    spotOnColorIn = a.getColor(R.styleable.Switch_spotOnColor, DEFAULT_SPOT_ON_COLOR_IN);
    spotOffColor = a.getColor(R.styleable.Switch_spotOffColor, DEFAULT_SPOT_OFF_COLOR);
    spotOffColorIn = a.getColor(R.styleable.Switch_spotOnColor, DEFAULT_SPOT_OFF_COLOR_IN);
    spotPadding = a.getDimensionPixelSize(R.styleable.Switch_spotPadding, dp2px(DEFAULT_SPOT_PADDING));
    switchOnStrokeColor = a.getColor(R.styleable.Switch_switchOnStrokeColor, switchOnColor);
    switchOffStrokeColor = a.getColor(R.styleable.Switch_switchOffStrokeColor, switchOffColor);
    duration = a.getInteger(R.styleable.Switch_duration, ANIMATION_DURATION);
    mChecked = a.getBoolean(R.styleable.Switch_checked, false);
    a.recycle();

    state = mChecked ? State.SWITCH_ON : State.SWITCH_OFF;
    setClickable(true);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);

    int width = dp2px(DEFAULT_WIDTH) + getPaddingLeft() + getPaddingRight();
    int height = dp2px(DEFAULT_HEIGHT) + getPaddingTop() + getPaddingBottom();

    if (widthSpecMode != MeasureSpec.AT_MOST) {
        width = Math.max(width, widthSpecSize);
    }

    if (heightSpecMode != MeasureSpec.AT_MOST) {
        height = Math.max(height, heightSpecSize);
    }

    setMeasuredDimension(width, height);

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int w = getWidth();
    int h = getHeight();
    int pl = getPaddingLeft();
    int pt = getPaddingTop();
    int pr = getPaddingRight();
    int pb = getPaddingBottom();
    int wp = w - pl - pr;
    int hp = h - pt - pb;
    int sw = dp2px(DEFAULT_WIDTH);
    int sh = dp2px(DEFAULT_HEIGHT);

    int dx = pl + (wp - sw) / 2;
    int dy = pt + (hp - sh) / 2;
    canvas.translate(dx, dy);

    switch (state) {
        case SWITCH_ON:
            drawSwitchOn(canvas);
            break;
        case SWITCH_OFF:
            drawSwitchOff(canvas);
            break;
        case SWITCH_ANIMATION_ON:
            drawSwitchOnAnim(canvas);
            break;
        case SWITCH_ANIMATION_OFF:
            drawSwitchOffAnim(canvas);
            break;
    }
}

private void drawSwitchOn(Canvas canvas) {
    float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
    drawRoundRect(canvas, switchOnColor, rectAttrs);

    float[] ovalAttrs = compOvalAttr(SWITCH_ON_POS);
    drawOval(canvas, spotOnColor, ovalAttrs);
    drawOvalIn(canvas, spotOnColorIn, ovalAttrs);

    drawRoundRectStroke(canvas, DEFAULT_SWITCH_ON_COLOR_OUT);
}

private void drawSwitchOff(Canvas canvas) {
    float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
    drawRoundRect(canvas, switchOffColor, rectAttrs);

    float[] ovalAttrs = compOvalAttr(SWITCH_OFF_POS);
    drawOval(canvas, spotOffColor,  ovalAttrs);
    drawOvalIn(canvas, spotOffColorIn, ovalAttrs);

    drawRoundRectStroke(canvas, DEFAULT_SWITCH_OFF_COLOR_OUT);
}

private void drawSwitchOnAnim(Canvas canvas) {
    float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
    drawRoundRect(canvas, switchOnColor, rectAttrs);

    rectAttrs = compRoundRectAttr(currentPos);
    drawRoundRect(canvas, switchOffColor, rectAttrs);

    float[] ovalShadeOnAttrs = compRoundRectShadeOnAttr(currentPos * 3/2);
    float[] ovalAttrs = compOvalAttr(currentPos* 3/2);
    int color = compColor(currentPos, DEFAULT_SPOT_OFF_COLOR, DEFAULT_SPOT_ON_COLOR);
    int colorIn = compColor(currentPos, DEFAULT_SPOT_OFF_COLOR_IN, DEFAULT_SPOT_ON_COLOR_IN);
    drawRoundRect(canvas, color, ovalShadeOnAttrs);
    drawOval(canvas, color, ovalAttrs);
    drawOvalIn(canvas, colorIn, ovalAttrs);

    int strokeColor = compColor(currentPos, DEFAULT_SWITCH_OFF_COLOR_OUT, DEFAULT_SWITCH_ON_COLOR_OUT);
    drawRoundRectStroke(canvas, strokeColor);
}

private void drawSwitchOffAnim(Canvas canvas) {
    float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
    if (currentPos != 1) {
        drawRoundRect(canvas, switchOffColor, rectAttrs);
    }

    rectAttrs = compRoundRectAttr(1 - currentPos);
    drawRoundRect(canvas, switchOffColor, rectAttrs);

    float[] ovalAttrs;
    if(currentPos > 2.0/3){
        ovalAttrs = compOvalAttr(0);
    }else{
        ovalAttrs = compOvalAttr(1 - currentPos * 3/2);
    }
    float[] ovalShadeOffAttrs = compRoundRectShadeOffAttr(1 - currentPos * 3/2);
    int color = compColor(currentPos, DEFAULT_SPOT_ON_COLOR, DEFAULT_SPOT_OFF_COLOR);
    int colorIn = compColor(currentPos, DEFAULT_SPOT_ON_COLOR_IN, DEFAULT_SPOT_OFF_COLOR_IN);
    drawRoundRect(canvas, color, ovalShadeOffAttrs);
    drawOval(canvas, color, ovalAttrs);
    drawOvalIn(canvas, colorIn, ovalAttrs);

    int strokeColor = compColor(currentPos, DEFAULT_SWITCH_ON_COLOR_OUT, DEFAULT_SWITCH_OFF_COLOR_OUT);
    drawRoundRectStroke(canvas, strokeColor);
}

private void drawRoundRect(Canvas canvas, int color, float[] attrs) {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.FILL);
    paint.setStrokeCap(Paint.Cap.ROUND);
    RectF rectF = new RectF();
    paint.setColor(color);
    rectF.set(attrs[0], attrs[1], attrs[2], attrs[3]);
    canvas.drawRoundRect(rectF, attrs[4], attrs[4], paint);
}

private void drawRoundRectStroke(Canvas canvas, int color) {
    int sw = dp2px(DEFAULT_WIDTH);
    int sh = dp2px(DEFAULT_HEIGHT);

    float left = dp2pxFloat((float) 2.4);
    float right = sw - left;
    float top = dp2pxFloat((float) 2.4);
    float bottom = sh - top;
    float radius = (bottom - top) * 0.5f;

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);
    paint.setStrokeWidth(dp2pxFloat((float) 3.6));
    RectF rectF = new RectF();
    rectF.set(left, top, right, bottom);
    canvas.drawRoundRect(rectF, radius, radius, paint);
}

private void drawOvalIn(Canvas canvas, int color, float[] attrs) {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(color);
    int borderWidth = dp2px(DEFAULT_BORDER_WIDTH);
    RectF rectFIn = new RectF(attrs[0] + borderWidth, attrs[1] + borderWidth, attrs[2] - borderWidth, attrs[3] - borderWidth);
    canvas.drawOval(rectFIn, paint);
}

private void drawOval(Canvas canvas, int color, float[] attrs) {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(color);
    RectF rectF = new RectF(attrs[0], attrs[1], attrs[2], attrs[3]);
    canvas.drawOval(rectF, paint);
}

private float[] compRoundRectAttr(float pos) {
    int sw = dp2px(DEFAULT_WIDTH);
    int sh = dp2px(DEFAULT_HEIGHT);

    float left = sw * pos;
    float right = sw - left;
    float top = sh * pos;
    float bottom = sh - top;
    float radius = (bottom - top) * 0.5f;

    return new float[]{left, top, right, bottom, radius};
}

private float[] compRoundRectShadeOnAttr(float pos) {
    int sw = dp2px(DEFAULT_WIDTH);
    int sh = dp2px(DEFAULT_HEIGHT);
    int oh = sh - 2 * spotPadding;
    float left, right, top, bottom;
    if(pos < 0.35){
        left = 0;
        right = spotPadding + (sw - sh) * pos + oh;
        top = spotPadding;
        bottom = oh + top;
    }else{
        left = spotPadding + (sw - sh) * pos *2/3;
        right = spotPadding + (sw - sh) * pos *2/3+ oh;
        top = spotPadding;
        bottom = oh + top;
    }
    float radius = (bottom - top) * 0.5f;
    return new float[]{left, top, right, bottom, radius};
}

private float[] compRoundRectShadeOffAttr(float pos) {
    int sw = dp2px(DEFAULT_WIDTH);
    int sh = dp2px(DEFAULT_HEIGHT);
    int oh = sh - 2 * spotPadding;
    float left, right, top, bottom;

    if(pos > 0.65){
        left = spotPadding + (sw - sh) * pos;
        right = sw - spotPadding;
        top = spotPadding;
        bottom = oh + top;
    }else{
        left = spotPadding + (sw - sh) * (2*pos + 1)/3;
        right = spotPadding + (sw - sh) * (2*pos + 1)/3 + oh;
        top = spotPadding;
        bottom = oh + top;
    }
    float radius = (bottom - top) * 0.5f;
    return new float[]{left, top, right, bottom, radius};
}

private float[] compOvalAttr(float pos) {
    if(pos > 1){
        pos = 1;
    }
    int sw = dp2px(DEFAULT_WIDTH);
    int sh = dp2px(DEFAULT_HEIGHT);
    int oh = sh - 2 * spotPadding;

    float left = spotPadding + (sw - sh) * pos;
    float right = left + oh;
    float top = spotPadding;
    float bottom = oh + top;

    return new float[]{left, top, right, bottom};
}

private int compColor(float fraction, int startColor, int endColor) {
    return (Integer) new ArgbEvaluator().evaluate(fraction, startColor, endColor);
}

@Override
public boolean performClick() {
    toggle();

    final boolean handled = super.performClick();
    if (!handled) {
        // View only makes a sound effect if the onClickListener was
        // called, so we'll need to make one here instead.
        playSoundEffect(SoundEffectConstants.CLICK);
    }

    return handled;
}

public int dp2px(float dpValue) {
    float scale = getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

public float dp2pxFloat(float dpValue) {
    float scale = getResources().getDisplayMetrics().density;
    return dpValue * scale + 0.5f;
}

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void setChecked(boolean checked) {
    if (isMoving) {
        return;
    }

    if (mChecked != checked) {
        mChecked = checked;

        // Avoid infinite recursions if setChecked() is called from a listener
        if (mBroadcasting) {
            return;
        }

        mBroadcasting = true;
        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, mChecked);
        }
        mBroadcasting = false;

        if (mChecked) {
            state = State.SWITCH_ANIMATION_ON;
        } else {
            state = State.SWITCH_ANIMATION_OFF;
        }

        if (isAttachedToWindow() && isLaidOut()) {
            animateToCheckedState();
        } else {
            // Immediately move the thumb to the new position.
            cancelPositionAnimator();
            currentPos = 0;
        }
    }
}

private void cancelPositionAnimator() {
    if (valueAnimator != null) {
        valueAnimator.cancel();
    }
}

private void animateToCheckedState() {
    valueAnimator = ValueAnimator.ofFloat(0, 1);
    valueAnimator.setDuration(duration);
    valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            currentPos = (float) animation.getAnimatedValue();
            invalidate();
        }
    });

    valueAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationStart(Animator animation) {
            super.onAnimationStart(animation);
            isMoving = true;
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            isMoving = false;
        }
    });

    if (!valueAnimator.isRunning()) {
        valueAnimator.start();
        currentPos = 0;
    }
}

public int getDuration() {
    return duration;
}

public void setDuration(int duration) {
    this.duration = duration;
}

@Override
public boolean isChecked() {
    return mChecked;
}

@Override
public void toggle() {
    setChecked(!mChecked);
}

public int getSwitchOnColor() {
    return switchOnColor;
}

public void setSwitchOnColor(@ColorInt int switchOnColor) {
    this.switchOnColor = switchOnColor;
    invalidate();
}

public int getSwitchOffColor() {
    return switchOffColor;
}

public void setSwitchOffColor(@ColorInt int switchOffColor) {
    this.switchOffColor = switchOffColor;
    invalidate();
}

public int getSpotOnColor() {
    return spotOnColor;
}

public void setSpotOnColor(@ColorInt int spotOnColor) {
    this.spotOnColor = spotOnColor;
    invalidate();
}

public int getSpotOffColor() {
    return spotOffColor;
}

public void setSpotOffColor(@ColorInt int spotOffColor) {
    this.spotOffColor = spotOffColor;
    invalidate();
}

public int getSpotPadding() {
    return spotPadding;
}

public void setSpotPadding(int spotPadding) {
    this.spotPadding = spotPadding;
    invalidate();
}

public int getSwitchOffStrokeColor() {
    return switchOffStrokeColor;
}

public void setSwitchOffStrokeColor(int switchOffStrokeColor) {
    this.switchOffStrokeColor = switchOffStrokeColor;
    invalidate();
}

public int getSwitchOnStrokeColor() {
    return switchOnStrokeColor;
}

public void setSwitchOnStrokeColor(int switchOnStrokeColor) {
    this.switchOnStrokeColor = switchOnStrokeColor;
    invalidate();
}

public OnCheckedChangeListener getOnCheckedChangeListener() {
    return onCheckedChangeListener;
}

public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
    this.onCheckedChangeListener = onCheckedChangeListener;
}

public interface OnCheckedChangeListener {
    /**
     * Called when the checked state of a switch has changed.
     *
     * @param s         The switch whose state has changed.
     * @param isChecked The new checked state of switch.
     */
    void onCheckedChanged(MySwitchButton s, boolean isChecked);
}

}

4 个答案:

答案 0 :(得分:0)

尝试使用在一段时间后检查值的处理程序,并相应地将交换机的状态自动更改为选中或取消选中。

Bundle.main.bundleIdentifier

答案 1 :(得分:0)

当切换状态发生变化时,您需要 set value in preferences

switchButton.setOnCheckedChangeListener(new MySwitchButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(MySwitchButton s, boolean isChecked) {
         setPreference(context,ischecked);
         //your code
    }

    });

编辑:

在你的oncreate()方法中,使用

 switchButton.setChecked(getPreference());

直接将getPreference()方法中的值返回为

public boolean getPreference() {
    SharedPreferences settings = this.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    //  Toast.makeText(this,"EMP ID is "+emp_id,Toast.LENGTH_LONG).show();
    Common.punchedIn = settings.getBoolean("punch", false);
    Toast.makeText(this,"PUNCH IN STATUS "+String.valueOf(Common.punchedIn),Toast.LENGTH_LONG).show();
    return Common.punchedIn;
}

答案 2 :(得分:0)

在检索共享偏好数据后,用此替换onCreate代码:

Assets/Plugins/x86_64

答案 3 :(得分:0)

对于所有面临类似问题的人来说,这就是我的做法

MySwitchButton类中有静态int变量,我只是交换了位置。它现在工作正常

getPreference();

    if (Common.punchedIn) {
        switchButton.setOnCheckedChangeListener(null);
        //switchButton.setChecked(false);
        punchStatus_text.setText("Punch Out");
        MySwitchButton.SWITCH_OFF_POS=1;
        MySwitchButton.SWITCH_ON_POS=0;
        //setColorPreference(AttendanceActivity.this,Color.GREEN,Color.RED);
    } else {
        switchButton.setOnCheckedChangeListener(null);
        //switchButton.setChecked(true);
        punchStatus_text.setText("Punch In");
        MySwitchButton.SWITCH_OFF_POS=0;
        MySwitchButton.SWITCH_ON_POS=1;
        //setColorPreference(AttendanceActivity.this,Color.RED,Color.GREEN);
    }