jvoh
jvoh

Reputation: 37

How to get values from programmatically created EditTexts?

I want to send some whole number from first activity to second one. That number is actually number of edittexts that i want to create.

for (int i = 0; i < num_from_first_activity; i++) {
        EditText editText = new EditText(getApplicationContext());
        final LinearLayout ll = findViewById(R.id.llid);
        ll.addView(editText);
}

After i filled up those fields with some data. How to get values from them when i click button?

Upvotes: 0

Views: 62

Answers (2)

Xenolion
Xenolion

Reputation: 12717

You have to loop in the same LinearLayout you added but now you take Value:

LinearLayout ll = findViewById(R.id.llid);
for(int i=0; i<num_from_first_activity; i++) {
    EditText editText = (EditText) ll.getChildAt(i);

}

So you can see you loop so you can make a method for that to obtain the right item remember casting it to EditText if and only if you know they are EditText like this:

private String getTextAtEditTextIndex(int index){
    LinearLayout ll = findViewById(R.id.llid);
    EditText editText = (EditText) ll.getChildAt(i);
    return editText.getText().toString();    
}

This method will be returning String from editText in the EditText at a particular index.

Upvotes: 0

KeLiuyue
KeLiuyue

Reputation: 8237

1.In your loop , you need not to call ll = findViewById(R.id.layout_actual_effect); .

2.Use LinearLayout as global variable , you can use it in other place

3.Use ll.getChildAt(position) to get View ,and use editText.getText().toString() to get value

4.Call createEditText before calling getValue

Try this .

private int num_from_first_activity = 3;
private LinearLayout ll;

/**
 * create EditText
 */
private void createEditText() {
    ll = findViewById(R.id.layout_actual_effect);
    for (int i = 0; i < num_from_first_activity; i++) {
        EditText editText = new EditText(getApplicationContext());
        ll.addView(editText);
    }
}

/**
 * get value from EditText
 *
 * @param position in LinearLayout
 * @return
 */
public String getValue(int position) {
    EditText editText = (EditText) ll.getChildAt(position);
    return editText.getText().toString();
}

Upvotes: 1

Related Questions