This question already has answers here:
How to hide soft keyboard on android after clicking outside EditText?
(49 answers)
Hide keypad in android while touching outside Edit Text Area
(3 answers)
Closed 4 years ago.
I have a fragment containing an EditText for search input and a ListView. I've got the search part working, but now I want to close the keyboard when the user clicks the on the screen outside of the EditText. I'd also like to consume the click event (because it is a ListView, if I don't consume the click event the user may accidentally click on a ListView item they didn't want to open)
I know how to do this in an activity, but it seems to be different for fragments.
What I've tried so far:
Implement View.OnClickListener in the fragment and implement onClick as such:
#Override
public void onClick(View v) {
System.out.println("onClick true");
if (!(v instanceof EditText)) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.
INPUT_METHOD_SERVICE);
if (getActivity().getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
}
}
This never seemed to post "onClick true" when I clicked.
Override onTouchEvent in the fragment's activity and implement onTouchEvent as such:
#Override
public boolean onTouchEvent(final MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.
INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
return true;
}
Any help would be greatly appreciated. Thanks in advance.
If I get you right you can try to use a OnFocusChangeListener:
yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
final InputMethodManager inputManager = (InputMethodManager) getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null && !hasFocus) {
inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
This is just a sample, but maybe it points into the right direction.
Related
I want to mimic android keyboard behavior when handling touch event. The android keyboard always hide every time I click somewhere else other the edit text and the keyboard. So far, I could mimic that's behavior using dispatchTouchEvent
Since it will detect for any dispatch touch even, whenever I click my keyboard button then it will close the keyboard it self. I wanna check if I click somewhere else other than my keyboard then hide the keyboard, else keep the keyboard on. I think I just missed piece of code and I can't find it what i missed here. It just need one single step to accomplish this. Please help.
Here my keyboard looks like
and here what i did so far
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (getCurrentFocus() != null) {
View view = getCurrentFocus();
//im not sure this condition would help
if (view == null) {
keyboard.setVisibility(View.GONE);
}
}
return super.dispatchTouchEvent(ev);
}
I can get the view object but i cant determine which view that i need to keep my keyboard on.
The other code (variable declaration)
PhoneKeyboard pk;
InputConnection ic;
LinearLayout keyboard;
pk = findViewById(R.id.phone_keyboard);
ic = phone_no.onCreateInputConnection(new EditorInfo());
pk.setInputConnection(ic);
Handling back pressed (mimic the android keyboard behavior)
#Override
public void onBackPressed(){
if(keyboard.getVisibility() == View.GONE)
super.onBackPressed();
else
keyboard.setVisibility(View.GONE);
}
How I handle request on the editText to make my keyboard visible
phone_no.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(
android.content.Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if(view.equals(phone_no) && keyboard.getVisibility() == View.GONE) {
phone_no.requestFocus();
keyboard.setVisibility(View.VISIBLE);
}
return false;
}
});
How I handle submit / enter event at my custom keyboard (for who need the solution for custom keyboard, maybe this post can help other:) )
phone_no.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(
android.content.Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if(view.equals(phone_no) && keyboard.getVisibility() == View.GONE) {
phone_no.requestFocus();
keyboard.setVisibility(View.VISIBLE);
}
return false;
}
});
Here is my snippet code for the keyboard layout view
<include
layout="#layout/layout_keyboard_phone_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Ps. I also have base activity and it extends to all my activity (if your solution required the base activity)
Update 1
I have try this method
phone_no.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
keyboard.setVisibility(View.GONE);
}
}
});
Is doing the same thing with the onDispatch event, whenever I click number on my custom keyboard, it also hide the keyboard. I need to check if the view others than the edit text and my custom keyboard then hide the keyboard else keep the keyboard on. Thank you
I have three edit-text fields. Of these fields I want to display the soft input keyboard only for the first field and disabled for the later two fields sice these are date and time fields.
Edit-Text 1 //Show the keyboard
Edit-Text 2 and 3 //Hide the keyboard
By using below code I'm able to disable the keyboard for field 2 and 3 but when the user has focus on field 1 the keyboard appears but didn't hide when user taps on field 2 or 3. Although when field 2 or 3 is tapped first no keyboard appears.
//Code to disable soft input keyboard
public static void disableSoftInputFromAppearing(EditText editText) {
if (Build.VERSION.SDK_INT >= 11) {
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);
} else {
editText.setRawInputType(InputType.TYPE_NULL);
editText.setFocusable(true);
}
How can I hide the soft input keyboard if its already open?
//activity
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
// fragment
public void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
// If edit-text loses the focus, hiding keyboard
edTxtMessage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isEditable){
v.setFocusable(true);
v.setFocusableInTouchMode(true);
} else {
edTxtMessage.setFocusable(false);
}
return false;
}
});
edTxtMessage.setOnFocusChangeListener(new View.OnFocusChangeListener({
#Override
public void onFocusChange(View view, boolean b) {
if (!b){
hideKeyboard(getContext(), view);
}
}
});
private void hideKeyboard(Context context, View view) {
if (view != null) {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
Easy way is using the xml
android:inputType="none"
android:textIsSelectable="true
You can set the two attributes to your edittext
android:focusable="false"
android:focusableInTouchMode="false"
Note: By this Your edittext is clickable for the date and time not focus to softkeyboard
Check if the current focus is not null, otherwise it might lead to a null pointer exception
if (getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
Ok - I've bonked my head quite a bit with this. I have a custom dialog which has multiple edittexts. I've set my layout so that it does not automatically focus on the first as both are initially filled with default values (thus the user may just press 'accept')
I want any edittext to clear itself when touched and open a keyboard for numeric input. They may change one or both fields. If they touch and do not input, the field should change back to a default value.
I have implemented this with setOnFocusChangedListeners in addition to the addTextChangedListeners.
My first problem occured with the realization that the keyboard was toggling itself open/closed when a user touched both edittexts. I resolved this by using SHOW_FORCED,HIDE_NOT_ALWAYS as parameters to toggleSoftInput. Note that this was the only set of parameters which kept the keyboard open when a second field was touched.
Unfortunately, this has created a second problem which I do not understand - on exiting the dialog, I can no longer close the keyboard (ie, it remains visible on the following view). Previously, when I did not make an effort to clear the input, keyboards closed out ok. Using SHOW_IMPLICIT (ignoring the toggle issue) also has no problem with an open keyboard being closed on exit.
So.. how the * do I get this to work?
Below are some relevant sections of code:
edQuantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
Log.i(TAG,"edQuantity focus changed");
if (hasFocus) {
Log.i(TAG,"edQuantity HAS FOCUS");
edQuantity.setHint("");
edQuantity.setText("");
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_NOT_ALWAYS);
}
// was the other field left empty after a change attempt?
if (String.valueOf(edPrice.getText()).length()==0) edPrice.setText("0.01");
}
});
edPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
Log.i(TAG,"edPrice focus changed");
if (hasFocus) {
Log.i(TAG,"edPrice HAS FOCUS");
edPrice.setHint("");
edPrice.setText("");
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_NOT_ALWAYS);
}
// was the other field left empty after a change attempt?
if (String.valueOf(edQuantity.getText()).length()==0) edQuantity.setText("1");
}
});
protected static void dismissCustomDialog(Dialog dialog, Context context) {
if (dialog != null) {
// hide the soft keyboard
if (dialog.getCurrentFocus() != null) {
Log.i(TAG,"trying to hide a keyboard");
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(dialog.getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
imm.hideSoftInputFromWindow(dialog.getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
if(dialog.isShowing()) dialog.dismiss();
}
}
As per my comment above, used a toggle to see if a keyboard was already opened.
I would like to know the best way to hide keyboard after entering the text to EditText.
1) setonfocuschangelistener : Does this listener is fired only, when the done button is pressed or when the focus changes from one EditText to other? When I used this method, I couldn't hide the keyboard.
2) setOnTouchListener : When I used this, I could hide the keyboard, but i doubt there might be an issue with this. In this case, I add the touch listener to the root LinearLayout. Following code I had used:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
txtUserName = (EditText)findViewById(R.id.txtUserName);
btnLogin = (Button)findViewById(R.id.btnLogin);
layoutView = (LinearLayout)findViewById(R.id.li);
layoutView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(txtUserName
.getWindowToken(), 0);
return true;
}
});
}
Inside the main LinearLayout, I am using other two LinearLayouts. The issue that i faced with the above code is that at some points when I pressed, the keyboard doesn't hides.
My doubt is that I am adding touch listener only with root layout, not giving touch listener with other inner layouts or other controls(TextView). When I touch over other controls or some points around the TextView(ie, inner layouts), keyboard doesn't hides.
That means do i need to add touchListener to all layouts or controls inside the root layout?
How this situation can be handled in a better way?
You can use this code
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditView.getWindowToken(), 0);
My answer on this question:
Add this method:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
If you want to hide keyboard when you touch screen, you can do by this way:
#Override
public boolean onTouchEvent(MotionEvent event) {
hideSoftKeyboard(LoginActivity.this);
return false;
}
Hope this will help you.
Try this :
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
it can be used to suppress the keyboard until the user actually touched the edittext view.
OR
inputManager.hideSoftInputFromWindow(editView.getWindowToken(), 0);
A simple check for null or a try-catch avoids the NullPointerException if no view is focused.
public void hideKeyboard(Activity activity) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null) {
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
Best way to hide keyboard, just dispatchDoneKey in your activity. Keyboard will be hidden if it is in visible state.
public void dispatchDoneKey() {
dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}
I want to create 1 edit text with the below condition:
- User can not focus on this control in normal.
- When user click on this control, soft-keyborad is displayed and user can input into this control
- When user press enter on this soft-keyborad or back on device, it is closed and back to normal view with control is not focus.
I tried the below code but not work :(
When starting, control is not focus: ok
When click on control, at the first click, control is focus but not display soft-keyborad
In the second click, display soft-keyborad
When press enter button in soft-keyborad: back to screen with control is not focus: OK
When press back button device, back to screen with control is still focus : not ok
public void onCreate(Bundle savedInstanceState)
{
final EditText txtSearch = (EditText)this.findViewById(R.id.p60004_txt_search_str);
txtSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtSearch.setFocusable(true);//(false);
txtSearch.setFocusableInTouchMode(true);
txtSearch.requestFocus();
}
});
txtSearch.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER))
{
String strSearch = txtSearch.getText().toString();
if (strSearch != null && strSearch != ""){
searchFriend(UserAPIConstants.FRIEND_SEARCH_TYPE_SC, strSearch);
}
hideSoftKeyboard(v);
txtSearch.setFocusable(false);
txtSearch.setFocusableInTouchMode(false);
}
return false;
}
});
public void hideSoftKeyboard (View view) {
InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
In your xml which has edittext put these values for the layout node
android:focusable="true"
android:focusableInTouchMode="true"
and dont put any focusable or focusable in touch mode attributes for your edittext..
Then in your code in onKey method remove thse lines..
txtSearch.setFocusable(false);
txtSearch.setFocusableInTouchMode(false);
and put
txtSearch.clearFocus();
And You should override this method
onBackPressed()
like this..
#Override
public void onBackPressed() {
txtSearch.clearFocus();
//hide the soft keyboard..
}
try commenting
hidekeyboard(v);
and the changes that Alex Lockwood suggested.
use this in onClick()
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
to close the keypad use
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);