2011-04-01 116 views
2

我使用以下視圖來繪製位圖並移動它。Android:如何添加按鈕和自定義視圖

public class DrawView extends View { 
    private ColorBall ball; 
    public DrawView(Context context) { 
    super(context); 
    setFocusable(true); 
    ball = new ColorBall(context,R.drawable.bol_groen, points); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) {  
     canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null); 
    } 

    public boolean onTouchEvent(MotionEvent event) {   
    switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
       // do stuff... 
    } 
} 

在首發活動中,佈局設置使用setContentView(new DrawView(this));

我想添加一個按鈕在屏幕上,當我按一下按鈕,我想添加一個新的位圖。如何在此屏幕上添加按鈕?

編輯:這是我的main.xml從XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
<Button android:text="Button" 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 
</Button> 
<com.example.DrawView 
android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 
</LinearLayout> 

回答

3

集活動的佈局。把那裏的按鈕和你的自定義視圖放在那裏(如果你不想讓它可見,你可以使它變爲無效)。

但做它之前,你應該有你的觀點

public DrawView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    setFocusable(true); 
    ball = new ColorBall(context,R.drawable.bol_groen, points); 
} 
+0

由於多了一個構造函數。上述xml是否正確?位圖不顯示.. – 2011-04-01 08:24:25

+0

@rohith我認爲佈局是好的。如果沒有overriden onMeasure方法,我從來沒有做過自定義視圖。嘗試使用Log in draw方法來知道視圖的實際大小和繪製的位圖的座標。 – Maxim 2011-04-01 08:43:11

+0

謝謝。得到它的工作。你能否也請告訴我怎樣才能點擊按鈕添加一個位圖。 – 2011-04-01 09:04:50