Android Widget – EditText

A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of
TextView that includes rich editing capabilities.

Creating a EditText

You can create a EditText instance either by declaring it inside a layout XML file or by instantiating it programmatically.
Below example will cover both ways of creating a EditText in the following sections.

Creating a EditText in a Layout File

Creating a EditText inside an Android layout XML file is done by inserting a EditText element into the layout file at the
place where you want the EditText. Here is an example layout file declaring a EditText:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <edittext android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignleft="@+id/button" android:layout_margintop="61dp" android:ems="10" android:hint="Enter Text" android:inputtype="text">
</edittext></relativelayout>

Once the layout file is used as the content view of an Activity subclass you can obtain a reference to the EditText instance like this:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText editView = (EditText) findViewById(R.id.edittext);
        //Either you can enter text by typing or set text as like below
        editView.setText("Java");
    }
}

You can also instantiate an Android EditText programmatically. Here is an Android EditText instantiation example:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout relativeLayout =
            (RelativeLayout) findViewById(R.id.rootlayout);
        EditText editView = new EditText(this);
        editView.setText("Hey one more EditText");
        relativeLayout.addView(editView);
    }
}