Thursday, June 23, 2016

Android Development - How to Make Buttons Respond

In the series of Android Development posts, I will go over the very basics of Android programming intended for complete beginners. I won't be able to explain every singe details of the code, so one will need to refer here for general details.

Say you have a button that you would like to respond when a user tabs on it. In the layout xml file in the res folder, you will need to have your button element defined similar to below:

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/send"
        android:onClick="buttonAction" />

The necessary field for assigning any actions to "clicks" on the button is the last field, android:onClick="buttonAction". What it says is that when the user pushes on the button, the program will execute buttonAction function. Of course, we will need to define such function in the activity java file.

...
public class MainActivity extends Activity {
...
    public void buttonAction(View v) {
        // insert code for action
    }
...
}

That's it!

No comments:

Post a Comment