Wednesday, September 5, 2012

Using Buttons in Android

Hi Friends today  we will learn to use the Buttons, EditText , and TextViews.
EditText are used to take input from user. (like Textbox in java).
TextViews are used to show something (like Label in java.)

Note :If you are new to android and have not create any application in Android the read this Create First Project in Android   and then proceed.

So what we are going to do ?
We will create an application "Calculator" which will perform addition and subtraction.
We will have two EditText to take inputs.
A text view to show the result
And two buttons:
Add Button : to perform addition
Subtract button: to perform subtraction.

Create a new Project named as "Calculator"  and give the name "CalculatorActivity" to your activity.

Edit the main.xml file

edit your main.xml file add "Butttons", "Textviews" and "Edittexts" ,
It should like below.( you can just copy the code and paste in amin.xml file)

                          

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   

    <TextView
        android:layout_marginTop="30dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="First Number" />

    <EditText
        android:id="@+id/FirstNumber"
        android:hint="First Number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone" >

        <requestFocus />

    </EditText>
   
   
   

    <TextView
         android:layout_marginTop="15dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Second  Number" />
    <EditText
        android:id="@+id/SecondNumber"
        android:hint="Second Number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone" />
   
   
   

    <TextView
        android:id="@+id/result"
        android:layout_marginTop="30dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="" />
   
   
   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal" >
        <Button
               android:id="@+id/buttonAdd"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ADD" />
         <Button
             android:id="@+id/buttonSubtract"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SUBTRACT" />

    </LinearLayout>
</LinearLayout>



Editing CalculatorActivity file


now open your CalculatorActivity file , it should look like 

public class CalculatorActivity extends Activity
{
            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
       
                   
                    // get the Id's for refference
                    final TextView textViewResult=(TextView)findViewById(R.id.result);
                    final EditText editTextFirstNumber=(EditText)findViewById(R.id.FirstNumber);
                    final EditText editTextSecondNumber=(EditText)findViewById(R.id.SecondNumber);
                    Button addButton=(Button)findViewById(R.id.buttonAdd);
                    Button subtractButton=(Button)findViewById(R.id.buttonSubtract);
                   
                   //  add Button OnclickListener
     
        addButton.setOnClickListener(new View.OnClickListener() {
         
            public void onClick(View v)
            {
                String strFirstNumber=editTextFirstNumber.getText().toString();
                String strSecondNumber=editTextSecondNumber.getText().toString();
              
                // If user has Entered Nothing
                if(strFirstNumber.equals("")||strSecondNumber.equals(""))
                {
                    Toast.makeText(getApplicationContext(), "Please Eneter Both the Numbers", Toast.LENGTH_LONG).show();
                    return;
                }
              
                int firstNumber=Integer.parseInt(strFirstNumber);
                int secondNumber=Integer.parseInt(strSecondNumber);
                  textViewResult.setText("Answer is : "+String.valueOf(firstNumber+secondNumber));
            }
        });
     
        subtractButton.setOnClickListener(new View.OnClickListener() {
         
            public void onClick(View v)
            {
                 String strFirstNumber=editTextFirstNumber.getText().toString();
                 String strSecondNumber=editTextSecondNumber.getText().toString();
               
                 // If User has Entered Nothing
                 if(strFirstNumber.equals("")||strSecondNumber.equals(""))
                 {
                     Toast.makeText(getApplicationContext(), "Please Eneter Bothe the Numbers", Toast.LENGTH_LONG).show();
                     return;
                 }
               
                 int firstNumber=Integer.parseInt(strFirstNumber);
                 int secondNumber=Integer.parseInt(strSecondNumber);
                  textViewResult.setText("Answer is : "+String.valueOf(firstNumber-secondNumber));
            }
        });

       
    }
}


now run your application  and perform add or subtract action.

                                             

 Hope you enjoyed the post .
Comments are Welcome






8 comments:

  1. really its a good tutorial for a person who is new to android world.such a great job done by you keep it up

    ReplyDelete
  2. (y) Thanks a bunch ! this is much helping but can u plz look forward on the images which are not showing so that one can compare his activity with yours ! TY

    ReplyDelete
  3. Thanks for the clear and comprehensible tutorial. However, it crashes when I type decimals. Any solution

    ReplyDelete
    Replies
    1. Use Double.parseDouble() instead of Integer.parseInt(). Double and float works with decimals

      Delete

  4. Thanks Dude.....Keep Going

    ReplyDelete
  5. thanks...very good

    ReplyDelete