dannyk
dannyk

Reputation: 31

Android Studio - Create an EditText with a click of a button

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.

Upvotes: 0

Views: 1918

Answers (2)

MazRoid
MazRoid

Reputation: 145

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);
    }
            }
        });
    }

Upvotes: 1

Sachin Solanki
Sachin Solanki

Reputation: 79

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.

Upvotes: 1

Related Questions