我一直試圖在幾次單擊按鈕後在畫布上繪製不同的矩形。它應該顯示不同的彩色矩形,每按一下按鈕,矩形就會保留在畫布上。矩形應該能夠在畫布上移動。我已經寫了視圖類,但我不知道如何在點擊按鈕後對活動實現onDraw()方法,也不知道如何創建不同顏色的矩形。畫布(onDraw)Android
我的main.xml文件上有4個按鈕。
public class DrawRectangle extends View {
public DrawRectangle(Context context){
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Rect ourRect = new Rect();
ourRect.set(0, 0, canvas.getWidth()/2, canvas.getHeight()/2);
Paint blue = new Paint();
blue.setColor(Color.BLUE);
blue.setStyle(Paint.Style.FILL);
//Draw to actual canvas
canvas.drawRect(ourRect, blue);
}
}
這是我的活動類。
public class MainActivity extends Activity {
Button bluebutton, redbutton, yellowbutton, greenbutton;
DrawRectangle dr;
Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dr = new DrawRectangle(this);
bluebutton = (Button)findViewById(R.id.bluebutton);
redbutton = (Button)findViewById(R.id.redbutton);
yellowbutton = (Button)findViewById(R.id.yellowbutton);
greenbutton = (Button)findViewById(R.id.greenbutton);
bluebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dr.onDraw();
}
});
}
}
我一定要實現onTouchListener以及使矩形可以移動?
請指教。謝謝。
感謝您的回覆和建議。我已經對我的代碼進行了修改,但是當按鈕被點擊時,矩形沒有被繪製。問題,我是否必須在我的xml上指定一個surfaceView? – pancakeleh
我已經設置了setContentView(); be = setContentView(dr);並繪製矩形。但4個按鈕失蹤。我如何保持按鈕和矩形? – pancakeleh
你能提供你的main.xml文件嗎? – industrychanger