0

我想从 NewGame 活动调用 Gameview 类中定义的 start 方法。基本上我想添加 onclicklistener 并希望在单击按钮时执行 start() 方法中指定的任务活动:

public class NewGame extends Activity implements OnClickListener {

GameView gameview;

@Override
public void onCreate (Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    //gameview=new GameView(this);
    setContentView(R.layout.activity_new_game);

    View startbutton=findViewById(R.id.start_button);

    startbutton.setOnClickListener(this);


}

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.start_button:
        gameview.start(this);
    }

}

看法:

   public class GameView extends View {
    Path circle;
    Paint cPaint;
    Paint tPaint;
    String z;
    GameView a;
    int i=65,strt,arc,leftx,topy,rightx,bottomy,maxx,maxy,minx,miny;
    boolean flag1,flag2,flag3;
    double n1,n2;
    int n,n3=180,n4,n5=90;
    float f1=180,f2=90;
    int width;
    int height;



    Random r=new Random();


    RectF  oval;



    public GameView(Context context,AttributeSet attrs ) {

        super(context,attrs);

        leftx=0;
        topy=60;
        rightx=150;
        bottomy=120;

        z= String.valueOf(Character.toChars(i));

        cPaint = new Paint();
        cPaint.setColor(Color.RED);


        strt=45;
        arc=315;

        n1=Math.random()*600;
        Log.d("random",z);
        this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));


        // cPaint.setStrokeWidth(2);

        tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        tPaint.setColor(Color.BLACK);
        float scale = getResources().getDisplayMetrics().scaledDensity;
        tPaint.setTextSize(20 * scale);
       }
    public void start(Context context)
    {
        if (flag2==false)
            new DrawThread(this);
    }
4

1 回答 1

0

您的gameView对象当前是null。如果你的XML布局文件中有它,你应该onCreate用这样的一行来实例化它:

gameView = (GameView) findViewById(R.id.gameView);//where gameView is the id specified in your layout file (R.layout.main, or something)

如果它不在您的布局文件中,您需要实例化它并将其添加到您的布局中:

gameView = new GameView(this);
gameView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ViewGroup content = (ViewGroup) findViewById(android.R.id.content).getRootView();
content.addView(gameView);

现在你不会得到空指针异常,你的游戏视图会填满屏幕。

于 2013-07-18T15:56:24.177 回答