Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android finishing activity from class view by touchEvent

I have got class GameActivity and in there a method setContentView(GameView). In class GameView which extends View I have got a method:

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 
        }
    }
}

As you can see in class GameView in method onTouchEvent() when I pressed the button I am changing the activity to MainActivity. My problem is: how to finish the activity from class view (first I have to finished the present activity and after that go to next activity), because method: finish() doesn't work?

like image 761
user1519221 Avatar asked Nov 29 '25 04:11

user1519221


1 Answers

Use getContext() which returns the activity context used to create the view :

public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
          ...   
          ((Activity)getContext()).finish();
    }
}
like image 133
Dalmas Avatar answered Nov 30 '25 16:11

Dalmas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!