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>

どこでも赤で描画する必要がありますが、代わりに空白の画面が表示されます。私がどこで間違っているのか考えていますか?

4

1 に答える 1

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_parentためwrap_content、コンストラクターpublic DrawView(Context context)が呼び出されないためです。

ただし、XML レイアウト ファイルでカスタム ビューを宣言せず、次のonCreate()ように直接設定する場合、これは機能します。

setContentView(new DrawView(this));
于 2012-08-02T15:49:32.030 に答える