我点击了arenalayout.xml中的骰子按钮(这个xml由'ArenaLayout'类显示)。但画布不会绘制字符2.我想...如果我点击骰子按钮然后我画char 2.
注意:点击骰子按钮后,Arena类中'haveFirstDiced'变量的值变为TRUE。 'Arena'类中的onDraw内部存在条件。 。 。如果'haveFirstDiced'变量具有TRUE值,则绘制char 2.
public class ArenaLayout extends Activity {
private Arena arena;
ImageButton diceButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.arena_layout);
diceButton = (ImageButton) findViewById(R.id.dice);
dice();
}
private void dice() {
diceButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
arena.dicing();
}
});
}
}
这是'竞技场'课程:
public class Arena extends View{
private Paint p;
private Handler threadHandler = new Handler();
private Bitmap char1;
private float x = 20, y = 300;
Canvas c;
boolean haveFirstDiced = false;
public Arena(Context context, AttributeSet aSet) {
super(context, aSet);
p = new Paint();
}
public void dicing() {
new Thread(new XXX()).start();
}
@Override
synchronized public void onDraw(Canvas canvas) {
char2 = BitmapFactory.decodeResource(getResources(), R.drawable.char_2);
if(haveFirstDiced == true) {
canvas.drawBitmap(char2,x,y,null);
}
}
class XXX implements Runnable {
@Override
public void run() {
threadHandler.post(new Runnable() {
@Override
public void run() {
haveFirstDiced = true;
}
});
}
}
}
答案 0 :(得分:1)
这是我见过的最复杂的解决方案。不需要线程,可运行或onDraw进行同步。这是它应该是什么:
private void dice() {
diceButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
arena.dicing();
}
});
}
public class Arena extends View{
private Paint p;
private Handler threadHandler = new Handler();
private Bitmap char2;
private float x = 20, y = 300;
Canvas c;
boolean haveFirstDiced = false;
public Arena(Context context, AttributeSet aSet) {
super(context, aSet);
p = new Paint();
char2 = BitmapFactory.decodeResource(getResources(), R.drawable.char_2);
}
public void dicing() {
haveFirstDiced = true;
invalidate();
}
@Override
public void onDraw(Canvas canvas) {
if(haveFirstDiced == true) {
canvas.drawBitmap(char2,x,y,null);
}
}
}