Jiajun Yang Jiajun Yang - 3 months ago 14
Android Question

Android, EditText not update the variable after pressing Done

I have an EditText that let me type in the an IP address:
In the xml:

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/enterIP"
android:layout_weight="1"
android:onClick="enterIP"
android:inputType="textPhonetic"
android:imeOptions="actionDone"
/>


I used android:imeOptions="actionDone" so that the input box will disappear after I press Done.
In the Java:

public void enterIP(View view) {
EditText theIP = (EditText) findViewById(R.id.enterIP);
try {
myIP = theIP.getText().toString();
validIP = ipvalidator.validate(myIP);
} catch (NullPointerException e)
{
Log.d("Error", "Input address is NULL.");
}
Toast.makeText(getApplicationContext(), "New IP is " + myIP, Toast.LENGTH_LONG).show();
}


However, the problem with this is that when I pressed Done, myIP still holds the old value. Only when I touch the EditText to bring up the input again the value is updated.

So how can I make sure myIP will be updated when Done is pressed. ?

Thanks

Answer

try this

 yourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //do something
                    myIP = theIP.getText().toString(); 
            validIP = ipvalidator.validate(myIP);
                }
                return false;
            }
        });