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!
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:The
Thermometer
that you're setting to 50 isn't the one that is actually drawn on the screen.