Where do I put the onTouchListener method in an android project?

414 views Asked by At

I've seen plenty of answers on how to use onTouchListener such as this code:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){

            // Do what you want
            return true;
        }
        return false;
    }
});

but it's never clear to me where I'm supposed to put this code in my project ? So far I've only been editing my MainActivity.java file, will I need to create another java file to house this code?

1

There are 1 answers

2
Sondering Narcissist On

Nope. Widget properties can just go into your MainActivity code. It should look something like this:

ImageButton imageButton = (ImageButton) findViewById(R.id.button); //instantiate the button
imageButton.setOnTouchListener(new OnTouchListener() {...}) //set the listener

The other (less common) way to do this is through XML. See this SO post for more on that.