仅当我在onDraw()中创建对象时,onDraw()方法才起作用 [英] onDraw() Method work only when i creating my object in the onDraw()

查看:117
本文介绍了仅当我在onDraw()中创建对象时,onDraw()方法才起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题.我不知道为什么不能在iniGame()方法中创建对象.当我从GameObject类创建对象并在onDraw()方法中使用方法render()无效时.仅当我在有效的onDraw()方法中创建所有相对对象时.

I got a problem. I don't know why I can't create a object for example in my iniGame() method. When I create a object from the GameObject class and use the method render() in the onDraw() method that doesn't work. ONLY when I create all relative object in the onDraw() method that works.

我的布局XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="de.fhflensburg.manichja.barrier51.GameActivity">

    <de.fhflensburg.manichja.barrier51.GameView
        android:id="@+id/gameView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/gameView"
        />
</RelativeLayout>

我的游戏活动:

package de.fhflensburg.manichja.barrier51;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class GameActivity extends AppCompatActivity {


    private GameView gameView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        gameView = new GameView(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_game, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

我的GameView

my GameView

    package de.fhflensburg.manichja.barrier51;

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.os.CountDownTimer;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.View;


    public class GameView extends View {

        private Canvas canvas;
        private Context context;
        private Paint peter;
        private GameObject ball;

        public GameView(Context context) {
            super(context);
            this.context = context;
            initGame();
        }

        public void initGame(){


            //ball.setSprite(R.drawable.menu_background);
        }

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

        public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        @Override
        public void onDraw(Canvas canvas){
            ball = new GameObject(this.context);
            this.canvas = canvas;
            peter = new Paint();
            peter.setColor(Color.BLUE);
            canvas.drawRect(100, 100, 200, 200, peter);
            ball.render(canvas,peter);
        }
}

我的GameObject代码

my GameObject code

package de.fhflensburg.manichja.barrier51;

    import android.content.Context;
    import android.content.res.ColorStateList;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.drawable.Drawable;
    import android.util.Log;
    import android.view.View;
    import android.widget.ImageView;
    import android.util.Size;


public class GameObject {
    private Size size;      // A color as stated as a resource in the XML file (thus, it is an int)
    private Point position; // A color as stated as a resource in the XML file (thus, it is an int)
    private int fillColor;      // A color as stated as a resource in the XML file (thus, it is an int)
    private int strokeColor;// A color as stated as a resource in the XML file (thus, it is an int)
    private int sprite;// A color as stated as a resource in the XML file (thus, it is an int)


 private Bitmap ourSprite;
    private Context conny;

    public GameObject(Context context)
    {
        this.conny = context;
        /*Paint myPaint = new Paint();
        myPaint.setColor(Color.rgb(0, 0, 0));
        myPaint.setStrokeWidth(10);
        c.drawRect(100, 100, 200, 200, myPaint);*/
    }

    /**
     * Sets the position of the GameObject on the screen.
     * @param position A Point instance with x and y
     */
    public void setPosition(Point position)
    {
        this.position = position;
    }

    /**
     * Sets the fill color of the game object. If it has a Sprite image, the assigned color will be ignored.
     * @param color A color resource, defined in the XML file (e.g. R.color.limegreen)
     */
    public void setFillColor(int color)
    {
        this.fillColor = color;
    }

    /**
     * Sets the stroke color of the game object. If it has a Sprite image, the assigned color will be ignored.
     * @param color A color resource, defined in the XML file (e.g. R.color.limegreen)
     */
    public void setStrokeColor(int color)
    {
        this.strokeColor = color;
    }

    /**
     * @return Delivers the current size of the GameObject
     */
    public Size getSize()
    {
        return size;
    }

    /**
     * @return Delivers the current position of the GameObject
     */
    public Point getPosition()
    {
        return position;
    }

    /**
     * @return Delivers the current position of the GameObject as stated in the XML file.
     */
    public int getFillColor()
    {
        return fillColor;
    }

    /**
     * @return Delivers the current stroke color of the GameObject as stated in the XML file.
     */
    public int getStrokeColor()
    {
        return strokeColor;
    }

    /**
     * Checks for a collision of this object with another instance of a GameObject.
     * @param obj The object to be checked for collision
     * @return Returns true if the objects' coordinates overlap at any pixel.
     */
    public boolean overlaps(GameObject obj)
    {
        if (getPosition().x < obj.getPosition().x + obj.getSize().getWidth() &&
                getPosition().x + getSize().getWidth() > obj.getPosition().x &&
                getPosition().y < obj.getPosition().y + obj.getSize().getHeight() &&
                getSize().getHeight() + getPosition().y > obj.getPosition().y)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * Sets the sprite image of the GameObject.
     * @param sprite A bitmap resource as defined in the XML file.
     */
    public void setSprite(int sprite) {

        Log.i("Peter", "Inigame get started"+sprite);
        this.sprite = sprite;
        ourSprite = BitmapFactory.decodeResource(this.conny.getResources(),R.drawable.menu_background);
    }

    /**
     * @return Delivers the sprite resource id as an Integer.
     */
    public Bitmap getSprite() {

        return ourSprite;
    }

    /**
     * Renders the object with the current attributes on the screen.
     */
    public void render(Canvas c,Paint paint)
    {
        c.drawRect(0,0,120,120,paint);
    }

}

推荐答案

您正在获取NullPointerException,因为可能未调用您的initGame.至少不在调用onDraw的对象上.
我的意思是您的GameView有两个实例.第一个实例是您使用以下命令手动创建的实例:

You are getting a NullPointerException because your initGame is probably not called. At least not on the Object where onDraw is called.
What I mean is that there are two instances of your GameView. The first instance is the one you create manually using:

gameView = new GameView(this);

第二个实例是从XML文件创建的,因为您正在定义:

The second instance is created from the XML-File, since you are defining:

<de.fhflensburg.manichja.barrier51.GameView
    android:id="@+id/gameView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

因此,第二个实例是由应用自动创建的.而且您一开始不知道这三个构造函数中的哪个被调用.您应该更改两件事:

So this second instance is created automatically by the App. And you don't know at the beginning, which of the three constructors is called. There are two things you should change:

  1. 在活动中,将gameView = new GameView(this);替换为gameView = (GameView) findViewById(R.id.gameView);.这将为您提供正确的GameView实例.有关更多详细信息,请参考 View-Doc .
  2. 在您的GameView类中,在所有三个构造函数中添加对initGame的调用.这样可以确保无论调用什么构造函数,都可以初始化元素.
  1. In your activity, replace gameView = new GameView(this); with gameView = (GameView) findViewById(R.id.gameView);. This will give you the correct instance of your GameView. Please refer to the View-Doc for more details.
  2. In your GameView class, add a call to initGame in all three constructors. This ensures that the elements are initialized, no matter what constructor is called.

这篇关于仅当我在onDraw()中创建对象时,onDraw()方法才起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆