You can get user text input from an EditText View.
First you have to add text inputs to your layout.
Give your EditText an ID attribute. I’m calling mine “firstName.”
Create the EditText as a Java object in your Activity class:
I’ve chosen to use the same name (“firstName”) for both the Java object and the ID in the layout, even though they are two different things.
This example also has a TextView and a ButtonĀ that I will use in a minute (see earlier examples)
getText() method
To retrieve what the user typed into the EditText, you can use the getText() method.
I’ll use that when the Button is clicked:
getText() returns a String.
firstName.getText() is equal to whatever the user typed into the firstName EditText View that’s calling its getText() method.
You can use getText() inside any other method that requires String input, such as Log.i() or setText().
You could also do something like this if you want to store the name for later use:
String fName = firstName.getText().toString();
Full example code:
You’ll have to import the classes (use “Alt-Enter”) and create an appropriate layout file.
For reference, here’s an XML layout for the example above:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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"> <LinearLayout android:layout_width="368dp" android:layout_height="495dp" android:orientation="vertical" tools:layout_editor_absoluteX="8dp" tools:layout_editor_absoluteY="8dp"> <TextView android:id="@+id/helloLabel" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="What is your name?" android:textAppearance="@android:style/TextAppearance.Large" android:textColor="@android:color/holo_green_dark" android:textSize="36sp"/> <EditText android:id="@+id/firstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:text="Name"/> <Button android:id="@+id/b1" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="clicked" android:text="Button"/> </LinearLayout> </android.support.constraint.ConstraintLayout>