Table of Contents

Android buttons and touch events

This tutorial shows how to add a button to your application and handle touch events.

Add button to your layout

  1. Go to app/res/layout/content_robot_layout.xml
  2. Drag and drp button from the menu on the left to the visualization of a mobile phone screen.
  3. Change the name and the ID of the button to something more unique, let's say ID: goForward and Text: FORWARD.
  4. Click on a Text representation of the layout and see how it is represented in XML (do not change anything, unless you know what you're doing)

Add touch listener

  1. Go to app/java/geist.re.mindroid/RobotControl
  2. Find onCreate method (it should be around line 123
  3. Insert the following code to add touch events handlers for your button (note, that the id of the button should be changed to whatever you name it):
    //Change the id here
    Button goForward = (Button) findViewById(R.id.button);
    goForward.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(robot == null || robot.getConnectionState() != RobotService.CONN_STATE_CONNECTED){
                return false;
            }
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    //Run motors
                    return true; // if you want to handle the touch event
                case MotionEvent.ACTION_UP:
                    //Stop motors
                    return true; // if you want to handle the touch event
            }
            return false;
        }
    });

Add onClick method

In case you just want to handle basic tap event, you can do it by adding onClick method to your button. Note, that releasing the button will not be handled.

  1. In text representation of the layout add onClick field to your button definition and assign it a namne of a function you want to call in case of tap event.
  2. In app/java/geist.re/mindroid/RobotControl add the function of the same name as in the previoud step, that takes View v as a parameter:
    public void goForward(View w){
    //Do some col stuff in here
    }
  3. That's it. Every time the user clicks the button, the function you've created will be called.