0

Can't seem to find a post/video on the net that explains adding new EditText fields with a button. I need to use the edittexts later. Can someone please explain to me how to create this system? Or link a video/post that explains this. I've been searching for a long time but I still haven't found a good explanation. Thanks.

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
dannyk
  • 31
  • 4
  • Hi! Welcome to stack overflow, if your question does not attract answer, check out https://stackoverflow.com/help/how-to-ask to get good tips on how to improve your question in StackOverFlow ;) – Sylhare Dec 13 '18 at 22:38
  • Have you already seen this post? [Android add edittext field on click of (+) button and remove by click of (-)](https://stackoverflow.com/questions/14935739/android-add-edittext-field-on-click-of-button-and-remove-by-click-of) I guess you have since you have been searching a long time, but seems there are a lot of existing Q&A on this site that would answer your question: put in google "add new EditText fields with a button site:stackoverflow.com" suggests that post and many other potential related questions. – chickity china chinese chicken Dec 14 '18 at 00:13
  • or this one? [Android - Add textview to layout when button is pressed](https://stackoverflow.com/questions/6930604/android-add-textview-to-layout-when-button-is-pressed/6932540#6932540) – chickity china chinese chicken Dec 14 '18 at 00:15
  • None of the codes found seem to work, since I always ended up getting an error. What I wanted is to someone explain how it works. And to answer your question, yes I have. – dannyk Dec 14 '18 at 15:14

2 Answers2

1
Button mButton = (Button) findViewById(R.id.my_button);
mButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        EditText t = new EditText(myContext);
        t.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        root.addView(t);
    } 
});

root: is the root layout where you want to add the EditText.

Sachin Solanki
  • 79
  • 2
  • 15
1

use below code

Add this Java File..

 LinearLayout linearLayout = findViewById(R.id.editTextContainer);  


    Button btnShow = findViewById(R.id.btnShow);
    if (btnShow != null) {
        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 // Create EditText
        final EditText editText = new EditText(this);
       editText.setHint(R.string.enter_something);
       editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
       editText.setPadding(20, 20, 20, 20);

    // Add EditText to LinearLayout  
    if (linearLayout != null) {
        linearLayout.addView(editText);
    }
            }
        });
    }
MazRoid
  • 145
  • 1
  • 12