Android 通过 touchEvent 从类 View 完成 Activity

标签 android view android-activity touch

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

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() 中看到的那样,当我按下按钮时,我将 Activity 更改为 MainActivity。我的问题是:如何从类 View 中完成 Activity (首先我必须完成当前 Activity 然后转到下一个 Activity ),因为方法: finish() 不起作用?

最佳答案

使用getContext()它返回用于创建 View 的 Activity 上下文:

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

关于Android 通过 touchEvent 从类 View 完成 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11679108/

相关文章:

java - 如何在 Android 中以编程方式设置背景可绘制对象

android - 不兼容的Gradle版本-Android

android - 在自定义 View 中提供默认样式(属性)

Android "wrong password or username "消息框显示错误

java - Android中的一个字符串存在于多个Activity中?

android - Google Play : Neon and FPU filters? 或没有它们如何生活?

Android : 4. 0.3 模拟器一段时间后自动关闭

android - 如何为新 fragment 重用 fragment View

android - 当应用程序移动到后台时,android 会清除 View 中的数据吗?

Android ==> 子 Activity ?