2012-08-02 119 views
2

剛剛開始Android開發,我在使用畫布簡單繪製視圖時遇到問題。安卓在畫布上繪製

據我瞭解,像這樣:

import android.content.Context; 
import android.graphics.Canvas; 
import android.view.View; 

public class DrawView extends View 
{ 
    public DrawView(Context context) 
    { 
     super(context); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) 
    { 
     super.onDraw(canvas); 
     canvas.drawRGB(255,0,0); 
    } 
} 

以此作爲我的活動:

public class Prototype1 extends Activity 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
    } 
} 

而本作的佈局:

<?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" 
    > 
    <com.dhs2.prototype1.DrawView 
     android:id="@+id/map" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     /> 
</LinearLayout> 

應該只是隨處繪製紅色,但我只是得到一個空白屏幕。 任何想法我哪裏錯了?

+0

你試過切換super.onDraw的順序()和canvas.drawRGB()? – scriptocalypse 2012-08-02 15:46:36

回答

5

既然你添加自定義視圖在一個XML配置文件,您應該添加2個構造函數:

public DrawView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
} 


public DrawView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

這是因爲你通過一些屬性的觀點,像fill_parentwrap_content,所以構造public DrawView(Context context)將不會被調用。

然而,這將工作,如果你不會宣佈在XML佈局文件自定義視圖,而是直接從onCreate()這樣設置的:

setContentView(new DrawView(this)); 
+0

感謝您加入正確的答案。另一件需要注意的事情是,當我試圖從原始問題運行代碼時,調試器「崩潰」,並且堆棧跟蹤表明該活動引發異常。問題說「顯示黑屏」表示程序成功運行,沒有例外。除了提供問題的答案之外,應該注意的是,注意調試器和logcat,並注意應用程序正在崩潰過程中非常重要。 – scriptocalypse 2012-08-02 15:56:14

+0

很高興我幫你。如果回答您的問題,請將答案標記爲已接受。 – 2012-08-03 07:26:54