Skip to content Skip to sidebar Skip to footer

Get Value From Programmatically Added Edittext In Fragment

I have a fragment. Inside that fragment I am programmatically creating edittext widgets as follows: driverItem = new EditText(getContext()); driverItemArray.add(driverItem); driver

Solution 1:

Try this it will save all EditText text in String array

String[] strings = newString[](driverItemArray.length);
for(int i=0; i < driverItemArray.length; i++){
    string[i] = driverItemArray[i].getText().toString();
}

Solution 2:

The way to do this is with the callback pattern. So when you make the fragment it accepts an interface. When the button is called it calls a method on that interface. The activity can then be the one implementing the interface to receive the event. Android Studio is even able to create the boilerplate for you.

Inside your fragment

@OverridepublicvoidonAttach(Context context) {
    super.onAttach(context);
    if (context instanceofOnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        thrownewRuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

On the button click listener

onReturnValue(driverItem.getText().toString())

The interface itself

public interface OnFragmentInteractionListener { void onReturnValue(String driverItem); }

The activity

publicclassMyActivityimplementsOnFragmentInteractionListener  {
    ....

    publicvoidonReturnValue(String value) {
       //youre inside the activity now so use the value
    }
}

Solution 3:

In Your Fragment declare driverItem as global variable and this method:

public String getEditTextValue() {
 return driverItem.getText().toString().trim();
}

From Activity you have an instance of the fragment. then call above method:

Stringvalue= fragmentInstance.getEditTextValue();

Post a Comment for "Get Value From Programmatically Added Edittext In Fragment"