【问题标题】:Android finishing activity from class view by touchEvent通过 touchEvent 从类视图中完成 Android 活动
【发布时间】:2012-07-26 22:44:18
【问题描述】:

我有一个 GameActivity 类,其中有一个方法 setContentView(GameView)。在扩展View 的类GameView 中,我有一个方法:

public class GameView extends View{
...
    public boolean onTouchEvent(MotionEvent event){
         switch(event.getAction()){ 
           case MotionEvent.ACTION_DOWN:    
            Intent intent = new Intent (contexTmp, MainActivity.class); 
            contexTmp.startActivity(intent); 
            //finish(); //->how to finish this activity from class view 
        }
    }
}

正如您在类GameView 中看到的那样,当我按下按钮时,方法onTouchEvent() 将活动更改为MainActivity。我的问题是:如何从班级视图完成活动(首先我必须完成当前活动,然后再进行下一个活动),因为方法: finish() 不起作用?

【问题讨论】:

  • 您必须获得对活动的引用并在其上调用完成方法

标签: android view android-activity touch


【解决方案1】:

使用getContext(),它返回用于创建视图的活动上下文:

public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
          ...   
          ((Activity)getContext()).finish();
    }
}

【讨论】:

    【解决方案2】:

    只要您的 GameView 是 Activity 中的视图之一,您就可以简单地调用:

    ((Activity)getContext()).finish();
    

    这将是创建视图的活动的上下文。因此,请确保这是您想要完成的活动,并且一切顺利!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      相关资源
      最近更新 更多