Wednesday 18 January 2017

Get EditText Value

Hello Viewers in following example i'll show you how to get values from edittext and display it on Toast.


In this tutorial i have used three components EditText, Button and Toast where :

EditText used for get values from user.

Button used for set any action while user press it.

Toast used to display information for the short period of time.

how to get value from edittext

Add following code in activity_main.xml file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.app.dipesh.getedittextvalue.MainActivity">

    <EditText
        android:id="@+id/etfname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter FirstName"/>

    <EditText
        android:id="@+id/etlname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter LastName"
        android:layout_marginTop="10dp"/>

    <Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal"/>


</LinearLayout>

Add following code MainActivity.java file:

package com.app.dipesh.getedittextvalue;

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.Toast;

public class MainActivity extends AppCompatActivity {

    EditText fname,lname;
    Button ok;

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

        //find all view using findViewById
        fname = (EditText) findViewById(R.id.etfname);
        lname = (EditText) findViewById(R.id.etlname);
        ok = (Button) findViewById(R.id.btnok);

        //set click listener on OK button
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fnm = fname.getText().toString().trim();
                String lnm = lname.getText().toString().trim();
                Toast.makeText(MainActivity.this,
                        "Fname is : " + fnm + " Lname is : " + lnm
                        , Toast.LENGTH_LONG).show();
            }
        });
    }

}

No comments:

Post a Comment