did:roboclub:android_tutorials:buttons
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
- Go to
app/res/layout/content_robot_layout.xml
- Drag and drp button from the menu on the left to the visualization of a mobile phone screen.
- Change the name and the ID of the button to something more unique, let's say ID:
goForward
and Text:FORWARD
. - 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
- Go to
app/java/geist.re.mindroid/RobotControl
- Find
onCreate
method (it should be around line 123 - 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.
- 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. - In
app/java/geist.re/mindroid/RobotControl
add the function of the same name as in the previoud step, that takesView v
as a parameter:public void goForward(View w){ //Do some col stuff in here }
- That's it. Every time the user clicks the button, the function you've created will be called.
did/roboclub/android_tutorials/buttons.txt · Last modified: 2024/10/10 09:22 by 127.0.0.1