2
\$\begingroup\$

I have two classes:

  • JoystickView (Extends View).
  • GameView (Extends SurfaceView): It will be updated by a Thread that call the onDraw Method.

Now, if I retrieve a direction by OnTouchEvent inside the JoystickView, how can send this information to the GameView? Can I use another thread for JoystickView and allow a communication between the thread of Joystick and the thread of the GameView? otherwise how can I do this?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Create a callback interface that the JoystickView fires when it sees an event, then make the GameView implement that interface and register itself as a listener to the JoystickView.

A simple approach could look something like this;

public interface JoystickListener {
  boolean onJoystickEvent(MotionEvent e);
}

public class JoystickView extends View {

  private JoystickListener listener;

  public void setListener(JoystickListener listener) {
    this.listener = listener;
  }

  @Override
  public boolean onTouchEvent(MotionEvent e) {
    if (listener != null) 
      listener.onJoystickEvent(e);
  } 
}

public class GameView extends SurfaceView implements JoystickListener {
  public boolean onJoystickEvent(MotionEvent e) {
    // Handle the joytstick event here
  }
}

public class YourGameActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    JoystickView jv = (JoystickView)findViewById(id_of_joystick_view);
    GameView gv = (GameView)findViewById(id_of_game_view);

    jv.setListener(gv);
  }
}

Note that the data passed to the listener does not have to be a MotionEvent, it would probably be better if it was something that had already figured out the relevant information from the MotionEvent.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .