繁体   English   中英

Android / Java:从类方法开始活动

[英]Android/Java: Starting activity from class method

我正在尝试从非活动类开始新的活动。

在主菜单中:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class Menu extends Activity {


    Button start, options;
    GameLoop Game = new GameLoop();

    @Override

    public void onCreate(Bundle mainStart) {
        super.onCreate(mainStart);
        setContentView(R.layout.menu);

    start = (Button) findViewById(R.id.bStart);

    options = (Button) findViewById(R.id.bOptions);

    start.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent openStart = new Intent(Menu.this, Game.class);
            startActivity(openStart);

        }
    });

    options.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Context mContext = null; //Error called for mContext to be initialized so just tried setting to null. This is most likely the error cause it would make more sense for it to be equal to "getContext()" or something like that
            Game.Start(mContext);//Here
        }
    });

    }

}

我正在尝试通过Game.Start()方法打开一个活动。

import android.content.Context;
import android.content.Intent;

public class GameLoop extends Menu{
    boolean hello = false;

    public void Start(Context sContext){
        Intent openOptions = new Intent(sContext, Options.class);
        startActivity(openOptions);

    }

}

我不确定使用上下文是否是解决此问题的正确方法,但我认为值得尝试。 我对Java和android完全陌生,所以我对下一步的工作很迷失。 朝任何方向的任何帮助将不胜感激。

您是否将新活动添加到了androidmanifest.xml中?

Activity扩展了Context,因此您可以在Activity中使用this

Game.Start(Menu.this);

我使用Menu.this是因为您位于内部匿名类(View.OnClickListener)中, this匿名类引用了这个内部类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM