How to create layouts that dynamically add and remove edited text at runtime… here is a solution to the problem.
How to create layouts that dynamically add and remove edited text at runtime
I’m working on a survey app and I need to know how to create a layout that lets the user enter multiple answers to a question, and once he enters the first text, then the next one should be dynamically generated below the first text
Also, How can I make edit text movable?
Solution
This code can help you
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Edit Text" >
</Button>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private Button buttonView;
private LinearLayout parentLayout;
private int hint=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonView=(Button)findViewById(R.id.buttonView);
parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
buttonView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TODO Auto-generated method stub
createEditTextView();
}
});
}
protected void createEditTextView() {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams (
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(0,10,0,10);
EditText edittTxt = new EditText(this);
int maxLength = 5;
hint++;
edittTxt.setHint("editText"+hint);
edittTxt.setLayoutParams(params);
edtTxt.setBackgroundColor(Color.WHITE);
edittTxt.setInputType(InputType.TYPE_CLASS_TEXT);
edittTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
edittTxt.setId(hint);
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edittTxt.setFilters(fArray);
parentLayout.addView(edittTxt);
}
}