简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM