How to make EditText regain focus?

2019-08-12 01:21发布

问题:

I have one activity with an EditText and a button. When the button is pressed, I call

myEditText.setClickable(false);
myEditText.setFocusable(false);

I have another button, which when pressed, changes the activity.

Intent myIntent = new Intent(view.getContext(), DestinationScreen.class);
startActivityForResult(myIntent, 0);

When I return from activity2 to my main activity which has the EditText, I want it to regain the focus. That is, I want to be able to type in some new values in it. Any idea how that is possible?

I tried to do this in my main Activity

startActivityForResult(myIntent, 0);
myEditText = (EditText) findViewById(R.id.textBox);
myEditText.setClickable(true);
myEditText.setFocusable(true);
myEditText.requestFocus();

It doesn't seem to work.

回答1:

As you said, you'd like the EditText to regain focus when you return from the second activity.
Then probably that's what you should try: since you are already invoking the activity2 with the startActivityForResult method (requestCode: 0), you could take advantage of it:

You should override the

onActivityResult(int requestCode, int resultCode, Intent data)

method inside your main activity, check whether the requestCode == 0, and if so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode)
    {
        case 0:
            EditText myEditText = (EditText) findViewById(R.id.textBox);
            myEditText.setClickable(true);
            myEditText.setFocusable(true);
            myEditText.requestFocus();
        default:
            break;
    }
}


回答2:

I haven't stepped through the Android source to fact check this, but the symptoms imply to me that:

  • #onActivityResult() is called sometime before #onResume(), and
  • requesting focus probably requires the view to be shown, which isn't true yet (because the activity's view hierarchy isn't attached to its window, see View#isShown()).

As such, you can fix it by requesting focus from a runnable on the main thread, which will run immediately after the activity is resumed. In your onActivityResult() definition:

final EditText myEditText = (EditText) findViewById(R.id.textBox);
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        myEditText.requestFocus();
        // Also move the cursor to the end
        myEditText.setSelection(myEditText.length());
    }
});