Custom view and member variables in Android

2019-08-17 18:41发布

I'm trying to create a animated custom view in Android but I'm having trouble with the view objects member variables. After i run invalidate() the variables get reinitialized.

I got this in my custom view called Thermometer

private float handTarget = 40;

public void setHandTarget(float temperature) {
    Log.e(TAG, "setHandTarget!");
    handTarget = temperature;
    Log.e(TAG, "handTarget="+handTarget);
    handInitialized = true;
    invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
    Log.e(TAG,"onDraw");
    drawBackground(canvas);

    float scale = (float) getWidth();       
    canvas.save(Canvas.MATRIX_SAVE_FLAG);
    canvas.scale(scale, scale);

    drawHand(canvas);

    canvas.restore();


    if (handNeedsToMove()) {
        moveHand();
    }

}
private boolean handNeedsToMove() {
    Log.e(TAG,"handNeedsToMove?? "+handPosition+" - "+handTarget);
    return Math.abs(handPosition - handTarget) > 0.01f;
}

And then I have this in my main activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Thermometer therm = new Thermometer(this);
    therm.setHandTarget(50);
}

When I run the app I get

setHandTarget!

handTarget=50.0

onDraw

handNeedsToMove?? 40.0 - 40.0

But what I expect is to get handNeedsToMove?? 40.0 - 50.0. Why do the handTarget variable not change? How to fix?

Many thanks in advance!

1条回答
仙女界的扛把子
2楼-- · 2019-08-17 19:26

I'm assuming you have a Thermometer in your main.xml layout?

You need to access the Thermometer that you set in your layout, like this:

Thermometer therm = (Thermometer) findViewById(R.id.thermo);
therm.setHandTarget(50);

The Thermometer that you're setting to 50 isn't the one that is actually drawn on the screen.

查看更多
登录 后发表回答