Create XML code for the design
activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><EditTextandroid:id="@+id/F"android:layout_width="151dp"android:layout_height="wrap_content"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:layout_marginTop="39dp"android:ems="10"android:inputType="numberDecimal"android:textSize="30dp"android:importantForAutofill="no" /><EditTextandroid:id="@+id/S"android:layout_width="151dp"android:layout_height="wrap_content"android:layout_alignTop="@+id/F"android:layout_alignParentEnd="true"android:ems="10"android:inputType="numberDecimal"android:textSize="30dp"/><Buttonandroid:id="@+id/Add"android:layout_width="151dp"android:layout_height="wrap_content"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:layout_marginTop="123dp"android:text="Add"android:textSize="25dp"/><Buttonandroid:id="@+id/Sub"android:layout_width="151dp"android:layout_height="wrap_content"android:layout_alignStart="@+id/S"android:layout_alignParentTop="true"android:layout_marginStart="5dp"android:layout_marginTop="118dp"android:text="Sub"android:textSize="25dp"/><TextViewandroid:id="@+id/Result"android:layout_width="151dp"android:layout_height="47dp"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="192dp"android:text="Result"android:textSize="30sp"/></RelativeLayout>
Create Class
But use your own package this creat default packageMainActivity.class
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText F,S; private Button Add, Sub; private TextView Result; Double Num1,Num2,Sum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Add =(Button)findViewById(R.id.Add); Sub =(Button)findViewById(R.id.Sub); Add.setOnClickListener(this); Sub.setOnClickListener(this); } @Override public void onClick(View v) { F =(EditText) findViewById(R.id.F); S =(EditText) findViewById(R.id.S); Result = (TextView) findViewById(R.id.Result); Num1 =Double.parseDouble(F.getText().toString()); Num2 = Double.parseDouble(S.getText().toString()); if (v.getId()==R.id.Add){ Sum=Num1+Num2; Result.setText(Double.toString(Sum)); } else if (v.getId()==R.id.Sub){ Sum=Num1-Num2; Result.setText(Double.toString(Sum)); } } }
0 on: "How to work Button action in android studio"
Your Comment is processing to approved