Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Adding a EditText programatically when a button is pressed

Tags:

android

layout

I am working on an SMS application. I have a "+" button so that when user clicks that button a new ExitText will appear under the existing one for user to enter multiple phone numbers to send the text. Can anyone please help with creating a new EditText when a button is pressed?

Thank You,

like image 236
aa051 Avatar asked Dec 12 '25 00:12

aa051


2 Answers

I would keep a List of EditText objects and add a new one

EditText toAdd = new EditText(this);
list.add(toAdd);

to the list on button press. Also, read this link for how to add that new EditText to your current layout. How to lay out Views in RelativeLayout programmatically?

When you know the user is done and wants to save the numbers, iterate through your List of EditText objects.

like image 64
Kevin King Avatar answered Dec 14 '25 15:12

Kevin King


I built an app that adds buttons dynamically based on how many rows there on in my database.

basically I found it easier to create an array of buttons with length equal to the number of buttons I need: In your case...

final int PHONE_NUMBERS = 0;

final int OTHER_STUFF = 1;

final int MORE_STUFF = 2;

LinearLayout MyEditTextLayout;

EditText []DynamicFields = new EditText[3];

*note these should be declared outside of onCreate*

then within onCreate {

MyEditTextLayout = (LinearLayout) findViewById (R.id.Whatever_you_named_your_layout_in_xml);

}

then in your onClickListener dialog:

final EditText editText = new EditText();

if(button = myPhoneNumberButton)
{

editText.layout_width = "fill_parent";

editText.hint = "Enter Phone Numbers Here";

DynamicFields[PHONE_NUMBERS] = editText; //that way you can refer to your editTexts later

MyEditTextLayout.addView(editText);

}

please note I typed this out quickly at work so the code might not work exactly as is but this should give you a good start Comment if you have any questions!

like image 21
Adam Storm Avatar answered Dec 14 '25 16:12

Adam Storm