Translate

Tuesday, December 25, 2012

Android App Development 101 2nd tutorial; xml, buttons, toast, switch case statement

In this tutorial i will be using the xml attributes that i discussed in the last tutorial. The goal of this tutorial is to familiarize with with some of the key concepts that are very common in android app development. We will be making an app that displays two buttons and when these buttons are clicked, a toast message with show up corresponding to that button. Toast messages are used in android when we have to display some message quick. For instance "push back again to exit" is one common toast message. Here is our code:

main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >

    <Button
        android:id="@+id/Button1"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:text="Button1"
        android:gravity="left|center"
        android:onClick="displayToast"/>
   
    <Button
        android:id="@+id/Button2"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:text="Button2"
        android:gravity="left|center"
        android:onClick="displayToast"/>
 

</LinearLayout>

Buttons.java


package com.peshal.testappbuttons;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;

public class Buttons extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void displayToast(View view) {


switch(view.getId()) {
case R.id.Button1:
Toast.makeText(getApplicationContext(), "Button 1 is Pressed", Toast.LENGTH_SHORT).show();
break;
case R.id.Button2:
Toast.makeText(getApplicationContext(), "Button 2 is Pressed", Toast.LENGTH_SHORT).show();
break;
}
}


}




1 comment: