limlim
limlim

Reputation: 3155

Remove focus from editText in dialog when keyboard is down

I have an AlertDialog with an edit text in it. When you hit the back key, the keyboard goes down (as it should), but the edit text is still with focus. If you hit the back key again, the whole dialog disappears.

I want to remove the focus from the edit text inside the dialog upon hiding the keyboard, but can't figure out how to.

Note that I don't want to override the onBackPressed or something similar, because I just want to control what happens when the back button is pressed when the dialog is up.

Any ideas?

Upvotes: 1

Views: 1743

Answers (2)

limlim
limlim

Reputation: 3155

The solution to my problem was partially as @kabuto178 said - I used a focusable frameLayout as the parent of my EditText, and then when called the edittext.clearFocus() upon hitting the back key, the parent frameLayout gained the focus:

final FrameLayout parent = new FrameLayout(context);
final EditText v = new EditText(context);
parent.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
parent.addView(v);
parent.setFocusableInTouchMode(true);
v.requestFocus();

Upvotes: 1

kabuto178
kabuto178

Reputation: 3167

Well the EditText widget has a method that can be used edittext.clearFocus(); sets the focus back to the first focusable view in the activity, but if you have only one view in the activity then there will be no other view to shift the focus to or you can manually set focus to another view in the layout which will remove the cursor. To get control of focus on the backpressed you have to override the onBackPressed() as I know it.

Upvotes: 0

Related Questions