我尝试将数据从MainActivity传递到我的类VistaJuego,它会在屏幕上移动玩偶但当它与障碍物碰撞时,游戏停止并且有意图应该转到另一个活动。我需要MainActivity的上下文来实现我的意图,但Eclipse总是显示NullPointerException。
我的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);
}
我的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){
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();
}
答案 0 :(得分:0)
如果要启动活动,请使用上下文而非活动
示例:
public void whenBeanCrash(Grafico elementofaba,Grafico elementoBotella){
// ...
// and not main.goToActivityLosed()
Context context = getContext();
context.startActivity(new Intent(context, YourActivity.class));
}
或者您可以创建一个设置活动对象的函数:
public void setActivity(MainActivity activity){
this.activity = activity;
// and now in whenBeanCrash() you can use this.activity to call function from this class
}