Create EditText dynamically using Java file in android

Android create EditText programmatically.

EditText view can also supports dynamic creation through MainActivity.java programming file. All you have to do is define EditText into mainactivity file. So here is the complete step by step tutorial for Create EditText dynamically using Java file in android.

android-project-download-code-button

Create EditText dynamically using Java file in android.

Code for MainActivity.java file.

 package com.android_examples.com.dynamicedittextview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 LayoutParams lParamsMW = new LinearLayout.LayoutParams(
 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
 
 LinearLayout linearLayout = new LinearLayout(this);
 linearLayout.setOrientation(LinearLayout.VERTICAL);
 
 EditText edtView = new EditText(this);
 edtView.setHint("Please enter your name");
 edtView.setLayoutParams(lParamsMW);
 edtView.setPadding(2, 2, 2, 2);
 lParamsMW.setMargins(50, 300, 30, 100);
 
 linearLayout.addView(edtView);
 
 this.setContentView(linearLayout, new LinearLayout.LayoutParams(
 LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

 }
}

Code for activity_main.xml layout file.

 <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:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.dynamicedittextview.MainActivity" >

</RelativeLayout>

Screenshot:

Create EditText dynamically using Java file in android

Click Here to Download Create EditText dynamically using Java file in android project.

Leave a Reply

Your email address will not be published. Required fields are marked *