Thursday, February 15, 2018

Deeveloping Simple Calculator App in Android

In previous you learned about textview, edittext , buttons and their most commonly used attributes, lets put all these together and develop an Android App which uses all these viws and their attributes.




Demp Application :  “Simple Calculator”



What we will do : We create a layout in which we have user will enter two numbers abd perform “Addition” and “Subtraction” operations.
Our layout will have following views
1: TextView1: to show label “First Number”
2: EditText1: to enter the first number
3: TextView2: to show label “Second Number”
4: EditText: to get the second number
5: Button Add: for Addition
6: Button Subtract: for Subtraction
7: TextView3: to show the answer




When user clicks on ADD or SUBTARCT button we first check that user has entered some number in the edit text and make sure that he/she has not left it blank, if user has left any of the edittext blank we will show a message “Please Enter Both the Numbers”. If user has entered both the numbers , we will perform the operation and show the result in textview3.




Create a new  Android Application named “Calculator” and edit files as below



AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.calculator"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.calculator.CalculatorMainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



activity_calculator_main.xml


<?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 for First Number -->

    <TextView
        android:layout_marginTop="30dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="#660033"
        android:layout_marginLeft="5dp"
        android:textStyle="bold"
        android:text="First Number" />
   
<!-- EditText for First Number-->

    <EditText
        android:id="@+id/editTextFirstNumber"
        android:hint="First Number"
        android:layout_marginLeft="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number" >

        <requestFocus />

    </EditText>
   
   
   
<!--  TextView for Second Number -->

    <TextView
        android:layout_marginTop="15dp"
        android:layout_marginLeft="5dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="#660033"
        android:textStyle="bold"
        android:text="Second  Number" />
   
<!-- EditText for Second Number-->

    <EditText
        android:id="@+id/editTextSecondNumber"
        android:layout_marginLeft="10dp"
        android:hint="Second Number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number" />
<!--  TextView to Show Result -->

    <TextView
        android:id="@+id/textViewResult"
        android:layout_marginTop="30dp"
        android:textSize="25dp"
        android:textColor="#0000CC"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Result" />
   
   
   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal" >
       
       <!--  Button for Addition -->
        <Button
            android:id="@+id/buttonAdd"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ADD" />
       
         <!--  Button for Subtraction -->
         <Button
            android:id="@+id/buttonSubtract"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SUBTRACT" />

    </LinearLayout>
</LinearLayout>






CalculatorMainActivity.java
public class CalculatorMainActivity extends Activity
{

   TextView textViewResult;
   EditText editTextFirstNumber,editTextSecondNumber;
   Button addButton,subtractButton;
                    
   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_calculator_main);
                                 
      // get the  for refferences of textView, and EditTexts
      textViewResult=(TextView)findViewById(R.id.textViewResult);
      editTextFirstNumber=(EditText)findViewById(R.id.editTextFirstNumber);
      editTextSecondNumber=(EditText)findViewById(R.id.editTextSecondNumber);
                   
      // get the  for refferences of both the buttons
       addButton=(Button)findViewById(R.id.buttonAdd);
       subtractButton=(Button)findViewById(R.id.buttonSubtract);
                   
                   
       // set clickListener on add Button
                   
       addButton.setOnClickListener(new View.OnClickListener() {
                     
        public void onClick(View v)
        {
          // Get the first number entered by user
           String strFirstNumber=editTextFirstNumber.getText().toString();
          // Get the second number entered by user
           String strSecondNumber=editTextSecondNumber.getText().toString();
                          
          /* Check If user has Entered Nothing in either of the Number editText
           *if any of the number contains blank string means user has entered     nothing */
           if(strFirstNumber.equals("")||strSecondNumber.equals(""))
            {
               Toast.makeText(getApplicationContext(), "Please Eneter Both the Numbers", Toast.LENGTH_LONG).show();
               return;
            }
                          
         // Convert both the Number String to Integer
           int firstNumber=Integer.parseInt(strFirstNumber);
           int secondNumber=Integer.parseInt(strSecondNumber);

           // perform addition     
             int  result=firstNumber+secondNumber;
                            
                                        
                           
/* Convert the result to String type because we have to show the             result in String form through textView  */
                     String resultString= String.valueOf(result);
                           
                      // show the result in textViewResult
                      textViewResult.setText("Answer is : "+resultString);
                     }
                });



                 
              //  set clickListener on subtract button Button
                subtractButton.setOnClickListener(new View.OnClickListener() {
                     
                 public void onClick(View v)
                 {
                    // Get the first number entered by user
                     String strFirstNumber=editTextFirstNumber.getText().toString();
                     // Get the second number entered by user
                     String strSecondNumber=editTextSecondNumber.getText().toString();
                          
               /* Check If user has Entered Nothing in either of the Number
editText if any of the number contains blank string means user has  entered nothing */
                   if(strFirstNumber.equals("")||strSecondNumber.equals(""))
                   {
                        Toast.makeText(getApplicationContext(), "Please Eneter Both the Numbers", Toast.LENGTH_LONG).show();
                       return;
                   }
                          
                  // Convert both the Number String to Integer
                  int firstNumber=Integer.parseInt(strFirstNumber);
                  int secondNumber=Integer.parseInt(strSecondNumber);
                       
                   // perform subtraction     
                  int result=firstNumber-secondNumber;
                           
                /* Convert the result to String type because we have to show
                    the result in String form through textView */
                  String resultString= String.valueOf(result);
                           
                  // show the result in textViewResult
                  textViewResult.setText("Answer is : "+resultString);
                 }
              });

                   
         }
                          
}


No comments:

Post a Comment