-----------------------------------------------------
XML Code
-----------------------------------------------------
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/num1"
android:hint="First Number"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/num2"
android:hint="Second Number"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/res"
android:hint="Result "
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/add"
android:text="Add"
android:onClick="perfrom"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/sub"
android:text="Sub"
android:onClick="perfrom"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/mul"
android:text="mul"
android:onClick="perfrom"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/div"
android:text="div"
android:onClick="perfrom"
/>
</LinearLayout>
-----------------------------------------------------
Java Code
-----------------------------------------------------
package com.example.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText e1,e2,e3;
int n1,n2,ans;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.num1);
e2 = (EditText)findViewById(R.id.num2);
e3 = (EditText)findViewById(R.id.res);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items
to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void perfrom(View v)
{
Button b = (Button)v;
n1 = Integer.parseInt(e1.getText().toString());
n2 = Integer.parseInt(e2.getText().toString());
switch(b.getId())
{
case R.id.add:
ans=n1+n2;
e3.setText(ans + "");
break;
case R.id.sub:
ans=n1-n2;
e3.setText(ans + "");
break;
case R.id.mul:
ans=n1*n2;
e3.setText(ans + "");
break;
case R.id.div:
ans=n1/n2;
e3.setText(ans + "");
break;
}
}
}
No comments:
Post a Comment