Alex Haycock
Alex Haycock

Reputation: 395

Is it possible to use an intent in a class which extends a view?

I'm making a turn based RPG game for Android. I have a class which extends a view which I need to launch another class also extending a view. The first class is where the player walks around the map and the second class will be the battle screen. I've tried to get it working but I get this error.

The constructor Intent(GameView, Class<BattleView>) is undefined

I have used intents before without any problems at all but I have never tried to use an intent in a class which extends a view. I presume this is why I am having problems. Is it possible to use an intent in a class which extends a view?

Any ideas?

Upvotes: 1

Views: 788

Answers (1)

Matt Wolfe
Matt Wolfe

Reputation: 9284

The constructor for Intent that you are looking for takes a context and then the class which you want to launch (an activity).

From your view class you should be able to do this:

Intent intentToLaunch = new Intent(getContext(), BattleView.class);

This will create your Intent correctly but you won't be able to launch the Activity from your view unless you pass in your Activity to your view, which is a really bad idea. Really this is a poor design as your view shouldn't be launching other activities. Instead, your view should makes calls to an Interface which the creator of that view will respond to.

It might look something like this:

public class GameView extends View {

  public interface GameViewInterface {
    void onEnterBattlefield();

  }
  private GameViewInterface mGameViewInterface;
  public GameView(Context context, GameViewInterface gameViewCallbacks) {
      super(context);
      mGameViewInterface = gameViewCallbacks;
  }

  //I have no idea where you are determining that they've entered the battlefield but lets pretend it's in the draw method
  @Override
  public void draw(Canvas canvas) {

     if (theyEnteredTheBattlefield) {
       mGameViewInterface.onEnterBattlefield();
     } 
  }

}

Now most likely you are creating this view from an Activity class so in that class, just create an instance of GameViewInterface. When you get the call to onEnterBattlefield() in your Activity, call startActivity with the intent I showed you.

Upvotes: 2

Related Questions