简体   繁体   English

传递数据从活动移至类可扩展视图

[英]Pass Data Moving from activity to Class extends View

i'm trying pass data from MainActivity to my class VistaJuego which draws a doll moving on the screen but when it collides with obstacles , the game stops and with an intent should go to another activity. 我正在尝试将数据从MainActivity传递到我的类VistaJuego,该类绘制一个在屏幕上移动的玩偶,但当它与障碍物碰撞时,游戏将停止,并有意图进行其他活动。 I need the context of my MainActivity to do my intent but Eclipse always show NullPointerException. 我需要MainActivity的上下文来实现我的意图,但是Eclipse始终显示NullPointerException。

my MainActivity public class MainActivity extends Activity { RelativeLayout relative; 我的MainActivity公共类MainActivity扩展了Activity {RelativeLayout相对; static Activity ac; 静态活动交流;

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    vistafaba=(VistaJuego)findViewById(R.id.faba);
    relative=(RelativeLayout)findViewById(R.id.relative);
    ac=this.getActivity();
}
public void goToActivityLosed(){
    Intent i= new Intent(this,ActivityLosed.class);
    startActivity(i);
} 

And my VistaJuego 还有我的VistaJuego

 public class VistaJuego extends View {



ThreadJuego juego = new ThreadJuego();
ThreadFaba hiloFaba= new ThreadFaba();

MainActivity main;

public VistaJuego(Context context, AttributeSet attrs) {
    super(context, attrs);
    //dialogo= new DialogoFinJuego(MainActivity.this);
    main= new MainActivity();

} public void whenBeanCrash(Grafico elementofaba,Grafico elementoBotella){ }当beanCrash(Grafico elementofaba,Grafico elementoBotella){

    if((elementofaba.getPosX()+elementofaba.getAncho()>=elementoBotella.getPosX()+15)&&
            (elementofaba.getPosX()+elementofaba.getAncho() <= elementoBotella.getPosX()+elementoBotella.getAncho()+15)&&
            (elementofaba.getPosY()+elementofaba.getAlto()>=elementoBotella.getPosY())
            && (elementofaba.getPosY()+elementofaba.getAlto() <= elementoBotella.getPosY()+elementoBotella.getAlto())){
        juego.detener();
        hiloFaba.detener();

        main.goToActivityLosed();

    }

If you want to start an activity use context not Activity 如果要启动活动,请使用上下文而不是活动

Example: 例:

public void whenBeanCrash(Grafico elementofaba,Grafico elementoBotella){
     // ...
     // and not main.goToActivityLosed()
     Context context = getContext();
     context.startActivity(new Intent(context, YourActivity.class));
}

Or you can create a function to set an activity object: 或者,您可以创建一个函数来设置活动对象:

public void setActivity(MainActivity activity){
       this.activity = activity;
       // and now in whenBeanCrash() you can use this.activity to call function from this class
}

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

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