Wednesday, 28 January 2015

Android working with buttons and Edit text

Step 1 :
Make a project.
Step 2 :
Paste the following code in MailActivity.java file.
package com.example.buttonexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
       private EditText edittext1, edittext2;
       private Button buttonSum;

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

              addListenerOnButton();

       }

       public void addListenerOnButton() {
              edittext1 = (EditText) findViewById(R.id.editText1);
              edittext2 = (EditText) findViewById(R.id.editText2);
              buttonSum = (Button) findViewById(R.id.button1);

              buttonSum.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View view) {
                           String value1 = edittext1.getText().toString();
                            String value2 = edittext2.getText().toString();
                           int a = Integer.parseInt(value1);
                           int b = Integer.parseInt(value2);
                           int sum = a + b;
                           Toast.makeText(getApplicationContext(), String.valueOf(sum),
                                         Toast.LENGTH_LONG).show();
                     }

              });

       }

}
Step 3 :
Paste the fllowing code in activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter first value" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter second value" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="115dp"
        android:text="Click" />


</LinearLayout>

No comments:

Post a Comment