How would I implement a button such that a new TextBox is added dynamically on each click?
Asked
Active
Viewed 1.4k times
1
-
i basically have a button lying on my xml file.. according to my knowledge..i have a clue that i have to do something in on click event... but thats where i m stuck. EditText ed = new EditText(context); view.addView(ed); so do i run a loop?? but with loop i will have defined number of edit text boxes.. but i want to add one by one.. so basically it acts like a plus button.. – Ripu Flora Oct 29 '11 at 08:38
-
Have a look [here](http://stackoverflow.com/questions/5918320/dynamically-add-textviews-to-a-linearlayout/5918524#5918524) – Adil Soomro Oct 29 '11 at 08:46
-
here he is defining the max number of edit textboxes.. i dont want that.. i want every time the button is clicked.. the edit box should come up.. – Ripu Flora Oct 29 '11 at 08:50
3 Answers
1
If you only, and always want to add two Edit Text widgets to your activity when the button is pressed you can do something like this (pseudo code). This assumes that you never want to have more than two edit text components beside your button.
<LinearLayout orientation="horizontal">
<Button >
<EditText id="@+id/et1" visibiltiy="gone" />
<EditText id="@+id/ed2" visibiltiy="gone" />
</LinearLayout>
in your button's onClick listener you can change the components visibility to visible by calling
findViewbyId(R.id.et1).setVisibility(Visible)
findViewbyId(R.id.et2).setVisibility(Visible)

Glenn Bech
- 6,103
- 4
- 39
- 56
-
umm ok kinda make sense... so everytime i will click the button the two edit boxes will pop up right? – Ripu Flora Oct 29 '11 at 08:44
-
Actually, they will pop up the first time you press the button, and stay there. Do you want them to go away, or add more EditTexts? Maybe you could explain your full problem and what you are trying to do? – Glenn Bech Oct 29 '11 at 09:08
0
You should have something like this:
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.
myContext: could be the activity, etc, etc.
Hope this helps!!

Dimitris Makris
- 5,183
- 2
- 34
- 54
-
dont we have to define root somewhere?? sorrie i m knew to android.. i am not very comfortable when it comes to dynamic... – Ripu Flora Oct 29 '11 at 08:55
-
Yeap, after you call setContentView(/*Your layout*/), supposing you have as a root of your xml a LinearLayout, you should do: LinearLayout root = (LinearLayout) findViewById(R.id.root_layout); – Dimitris Makris Oct 29 '11 at 09:00
0