Simple Calculator in Android

Adding Two Numbers App (Simple Calculator) in Android

Class File

package com.example.malik.test;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {

EditText editText1, editText2;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

public void onButtonClick(View view){

editText1 = (EditText) findViewById(R.id.etNum1);
editText2 = (EditText) findViewById(R.id.etNum2);
textView = (TextView) findViewById(R.id.tvResult);

int num1 = Integer.parseInt(editText1.getText().toString());
int num2 = Integer.parseInt(editText2.getText().toString());
int sum = num1 + num2;

textView.setText(Integer.toString(sum));
Toast.makeText(getApplicationContext(), Integer.toString(sum), Toast.LENGTH_SHORT).show();
}
}

 

XML FILE

 

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.example.malik.test.MainActivity”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceLarge”
android:text=”Result”
android:id=”@+id/tvResult” />

<EditText
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/etNum1″
android:layout_below=”@+id/tvResult”
android:layout_alignParentLeft=”true”
android:layout_alignParentStart=”true”
android:layout_marginTop=”65dp”
android:layout_alignParentRight=”true”
android:layout_alignParentEnd=”true”
android:hint=”Number 1″
android:gravity=”center”
/>

<EditText
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/etNum2″
android:layout_centerVertical=”true”
android:layout_alignParentLeft=”true”
android:layout_alignParentStart=”true”
android:layout_alignParentRight=”true”
android:layout_alignParentEnd=”true”
android:hint=”Number 2″
android:gravity=”center”
/>

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Sum”
android:id=”@+id/bSum”
android:layout_below=”@+id/etNum2″
android:layout_centerHorizontal=”true”
android:layout_marginTop=”67dp”
android:onClick=”onButtonClick” />
</RelativeLayout>

 

Output :

pic

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.