我无法理解为什么第一次在自定义视图中调用this.invalidate
时,方法onDraw()
被调用两次(对相同变量执行双重操作)。之后,每次用户按下按钮时,onDraw()
都会被调用一次。这是代码:
MyActivity
MyView mCustomView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interval_identification);
mCustomView = (MyView) findViewById(R.id.my_view);
Button mButton = (Button) findViewById(R.id.id_btn);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newDrawing();
}
});
newDrawing();
}
private void newDrawing() {
int a;
int b;
//some operations on 'a' and 'b'
mCustomView.newDrawing(a, b);
}
MyView的
int x;
int y;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Drawable object = ContextCompat.getDrawable(getContext(), R.drawable.object);
//some operations
object.draw(canvas); //based on 'x' and 'y'
}
public void newDrawing(int a, int b) {
x = a;
y = b;
this.invalidate();
}
答案 0 :(得分:0)
尝试在newDrawing();
的{{1}}方法中对newDrawing(); --> //newDrawing();
(onCreate
)发表评论。似乎系统首次自动调用MyActivity
。