在Android的自定义视图和成员变量 [英] Custom view and member variables in Android
问题描述
我想创建一个Android的动画自定义视图,但我在使用的视图对象的成员变量的麻烦。我运行无效()后,变量得到初始化。
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!
setHandTarget!
handTarget = 50.0
handTarget=50.0
的onDraw
handNeedsToMove? 40.0 - 40.0
handNeedsToMove?? 40.0 - 40.0
但我希望是让handNeedsToMove? 40.0 - 50.0。为什么在handTarget变量不会改变?如何解决?
But what I expect is to get handNeedsToMove?? 40.0 - 50.0. Why do the handTarget variable not change? How to fix?
提前感谢!
推荐答案
我假设你有一个温度计
在main.xml中的布局?
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);
的温度计
,你设置50个是不是在屏幕上画出实际的人。
The Thermometer
that you're setting to 50 isn't the one that is actually drawn on the screen.
这篇关于在Android的自定义视图和成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!