This is a basic problem of an inexperienced programmer. I am making a game in android application. Obviously it requires a lot of touch events. This function seems to grow very big with if/else statements. I want some guidelines on how to write an onTouchEvent method. Can someone point me to any example 开发者_开发问答that has a onTouchEvent method and how is it structured well ?
One of the nicest design patterns in Java is the observer (listener), I recommend using this rather than onTouchEvent(). The reason is that you can decouple the handling of events from the original control itself (i.e. Button) AND you don't have to subclass your control.
Here's a small example:
MyEventHandler myEvHandler = new MyEventHandler();
Button button = new Button();
button.setOnClickListener(myEvHandler);
// Basic Object Class called MyEventHandler
class MyEventHandler implements OnClickListener
{
public void onClick(View v)
{
if (v instanceof Button)
{
// handle the click event here.
}
}
}
Notice that you don't have to put the click-event logic in the button and best of all, you don't have to create a custom Button subclass.
You can do the same thing for any View and any UI Event.
精彩评论