Android Tutorials
In Android, an ‘EditText’ is a widget that accepts textual user input. It is one of the most widely used widgets in apps for all types of devices. If you’re accustomed to other programming languages, you may know the EditText as a Text Field, or a Text Box.
You must enter each line of code mentioned below in the same order, otherwise it won’t work.
Step One – Create The EditText
Go to the XML file of the user interface you are designing, click the ‘Design’ tab, then drag and drop an EditText onto your Activity (known to .NET and Borland IDE users as a form).
Step Two – Make The EditText Accessible In Your Java Code
Before you can control the EditText, get text from it, etc, you will have to import the EditText class. Go to the top of your Java file and type the following at the bottom of your list of ‘import’ statements:
import android.widget.EditText;
Next, go down to the procedure in which you want to control your EditText. As is the case with all Android widgets, you will have to find and declare the EditText using this line of code, for this example, I named it ‘my_textbox’, you can name it whatever you want:
EditText my_textbox = (EditText) findViewById(R.id.my_textbox);
Now you can finally do whatever you want with it!
Accepting User Input
Will the user type in a number or a string?
If you expect the user to type in letters (a string), then use the following code to get that string so you can interpret it, make decisions based on it, etc:
Your_Variable_Name = EditText.getText().toString();
You can just work with ‘Your_Variable_Name’ from now on (as long as your code is after the code I showed you above).
How To Accept A Decimal Number Using An EditText
in your UI’s XML file, type:
android:inputType=”numberDecimal”
Now declare the EditText to make it accessible from your Java code as I demonstrated above.
In this case, our variable will be a ‘Double’. Declare the variable:
Double Your_Variable_Name;
Now copy the number entered from the EditText to the variable as done above:
Your_Variable_Name = Double.parseDouble(my_textbox.getText().toString());
When you’re finished, your code should look like this:
Double Your_Variable_Name;
EditText my_textbox = (EditText) findViewById(R.id.my_textbox);
Your_Variable_Name = Double.parseDouble(my_textbox.getText().toString());
Now you can do whichever calculation you please with ‘Your_Variable_Name’.
Changing The Font Colour Of Your EditText
Go back to your XML file. In between, or after one of your ‘android:’ statements, type:
android:textColor=”@color/your_colour_name”
Or:
android: textColor=”hex code”
Therefore, if you want white text your code should be:
android:textColor=”#FFFFFF”
‘your_colour_name’ should be defined in your strings.xml file for this to work. This tutorial doesn’t cover that topic, so you can just use the hex code that represents your desired colour until you learn how to use strings.xml.
This code was tested in both Android Studio and ADT.