Reputation: 1733
I have to different EditText like these :
When I launch my activity, I instantly request focus on the EditText1. The only way to do so that is working is to add this on the onCreate :
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
EDITTEXT1.requestFocus();
When the user clicks on "Return" on his soft Keyboard, I want the EDITTEXT2 to obtain focus. So I added this :
EDITTEXT1.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == 66) { // CODE FOR RETURN
EDITTEXT2.requestFocus();
}
return false;
}
});
But when I do so, nothing happens. All my EditText are set FocusableInTouchMode and Focusable :
<EditText
android:id="@+id/EDITTEXT1"
android:layout_width="0dip"
android:layout_height="20dip"
android:layout_weight="2"
android:background="@color/White"
android:ems="10"
android:hint="My First EditText"
android:inputType="textCapWords"
android:padding="2dip"
android:singleLine="true"
android:textColor="@color/Black"
android:textSize="12dip" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/EDITTEXT2"
android:layout_width="0dip"
android:layout_height="20dip"
android:layout_weight="2"
android:background="@color/White"
android:ems="10"
android:hint="My Second EditText"
android:inputType="textCapWords"
android:padding="2dip"
android:singleLine="true"
android:textColor="@color/Black"
android:textSize="12dip" >
</EditText>
Do you have any idea on how I could focus the EDITTEXT2 after pressing OK on EDITTEXT1 ?
Thanks in advance!
Upvotes: 2
Views: 1512
Reputation: 1733
Thanks a lot for your answer. I finally found the easiest way to answer my own question :
Add :
android:nextFocusRight="@+id/EDITTEXT2"
To the properties of EDITTEXT1.
Nothing else is needed in order to go to the EDITTEXT2 after clicking "Enter" on EDITTEXT1.
Upvotes: 2
Reputation: 11
you should create your own EditText which extended from EditText firstly, then override the mothod dispatchKeyEventPreIme
like this:
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
return super.dispatchKeyEventPreIme(event);
} else if (event.getAction() == KeyEvent.ACTION_UP) {
hideInputMethod();
//change your focus at here
return true;
}
}
return super.dispatchKeyEventPreIme(event);
}
protected void hideInputMethod() {
InputMethodManager imm = (InputMethodManager)getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (null != imm) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
By the way, it not a good way to code like that if (keyCode == 66) { // CODE FOR RETURN
, and also 66 is not the value of back, it's key enter.
public static final int KEYCODE_ENTER = 66;
you'd better write KeyEvent.KEYCODE_BACK
or KeyEvent.KEYCODE_ENTER
instead.
I wish this could help you.
Upvotes: 0