Editext keyboard visibility on off programmatically Android - android

I am new to Android. I have one edit text when I click on it keyboard is showing automatically. But what I want to do is when user double tab on edit text should show the keyboard. How can I achieve it?
<Edit Text
android:id="#+id/TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="type something"/>
Here I take simple edit text.I take one Gesture Listener class to achieve double tap listener event.

Find the below code, it will check that the edittext is opened or not. If it is opened it will close it
yourEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourEditText= this.getCurrentFocus();
if (yourEditText!= null) {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) {
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
}
}
}
});

Why not use OnLongClickListener to achive what you want?
yourEditText .setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//show your keyboard
return false;
}
});
hide soft keyboard when click on edit text
yourEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
Here also read this post Android: How to detect double-tap? may help you to understand

Related

Hide to show and hide keyboard in DialogFragment

In my dialog fragment, I am able to show the keyboard using
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);
but I am not able to hide it on dismiss.
I've tried
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
and
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
neither of which work.
I've also tried showing and hiding the keyboard using
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(0, 0);
and
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
but these are not able to show or hide the keyboard.
public static class MyDialogFragment extends DialogFragment
{
#Nullable #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.my_input_dialog, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState)
{
super.onViewCreated(v, savedInstanceState);
final EditText editText = (EditText)v.findViewById(R.id.input);
// this line below is able to show the keyboard
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Button add = (Button)v.findViewById(R.id.add_btn);
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// other code not shown
dismiss();
}
});
Button cancel = (Button)v.findViewById(R.id.cancel_btn);
cancelButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dismiss();
}
});
}
#Override
public void onDismiss(DialogInterface dialog)
{
//this line below does NOT work, it does not hide the keyboard
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onDismiss(dialog);
}
}
Note: I have read these stackoverflow posts and have tried the proposed solutions to no avail:
How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event
Close/hide the Android Soft Keyboard
The solution turned out to a combination of the following. To show the keyboard in a DialogFragment:
#Override
public void onResume()
{
super.onResume();
editText.post(new Runnable()
{
#Override
public void run()
{
editText.requestFocus();
InputMethodManager imm =
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
}
To hide it, use the solution above by #Shekhar
#Override
public void onDismiss(DialogInterface dialog)
{
InputMethodManager imm =
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive())
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
super.onDismiss(dialog);
}
Hiding keyboard in a View inside DialogFragment:
public static void hideKeyboardInAndroidFragment(View view){
final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
For Hiding the Keyboard use this:
private void hideKeyboard() {
try {
InputMethodManager inputManager = (InputMethodManager) _activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(_activity.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
}
}
for hide soft keyboard, you can use this method:
public void hideSoftKeyboard() {
try {
View windowToken = getDialog().getWindow().getDecorView().getRootView();
InputMethodManager imm = (InputMethodManager) getDialog().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow( windowToken.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception ex) {
Log.e(ex);
}
}
Hide it in DialogFragment onDestroyView() method:
View view = getActivity().getCurrentFocus();
if (view == null) view = new View(activity);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm == null) return;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
maybe work.
I had extension for fragment, but didn't work with dialog fragment. This extension works for both (not tested much tho)
/**
* If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
*
* #param useReflection - whether to use reflection in case of no window token or not
*/
fun Fragment.hideKeyboard(context: Context = App.instance, useReflection: Boolean = true) {
val windowToken = view?.rootView?.windowToken
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
windowToken?.let {
imm.hideSoftInputFromWindow(windowToken, 0)
} ?: run {
if (useReflection) {
try {
if (getKeyboardHeight(imm) > 0) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}
} catch (exception: Exception) {
Timber.e(exception)
}
}
}
}
fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int
Edit: toggle opened keyboard if it was closed before, I use reflection to get keyboard's height, which is not best solution, but works
I found only one fully working approach if you want to show keyboard when dialog is shown and hide keyboard when dialog is dismissed
<style name="InputDialog" parent="ThemeOverlay.AppCompat.Dialog.Alert">
<item name="android:windowSoftInputMode">stateAlwaysVisible</item>
</style>
And then you should use the theme above inside your DialogFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.InputDialog)
}
Kotil Extension function for DialogFragment hide keyboard
use : hideKeyboard(view)
fun DialogFragment.hideKeyboard(view: View) {
val imm =view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}

Cannot hide Android soft keyboard even with inputmanager

Problem:
I want to hide the keyboard when the button "Add" is pressed. There are two EditText on the screen. The keyboard doesn't appear at starting the activity, which is good, but it doesn't go away on clicking button.
Here are all the possible questions from Stack Overflow that I have seen whose answers don't help me:
Close/hide the Android Soft Keyboard
Programmatically Hide/Show Android Soft Keyboard
How to hide Soft Keyboard when activity starts
How to hide soft keyboard on android after clicking outside EditText?
and many others.
Here is my code:
AddActivity
public class AddActivity extends ActionBarActivity {
EditText text1,text2;
DbHelper db;
ListView l;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
db = new DbHelper(this);
l = (ListView) findViewById(R.id.listInAddActivity);
text1 = (EditText) findViewById(R.id.i1);
text2 = (EditText) findViewById(R.id.i2);
// text1.setInputType(InputType.TYPE_NULL);
// text2.setInputType(InputType.TYPE_NULL);
hideKeyboard();
loadDataInAdd();
}
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1,s2);
loadDataInAdd();
hideKeyboard();
}
public void loadDataInAdd()
{
try {
Cursor cursor = db.fetchData();
ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.tasks,
cursor,
new String[]{db._ID, db.COLUMN_1, db.COLUMN_2},
new int[]{R.id.idnum, R.id.c1, R.id.c2}, 0);
l.setAdapter(myAdapter);
}
catch(NullPointerException e)
{
e.printStackTrace();
}
// MainActivity.loadData();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Most answers are about the InputManager method, but it does not work for me, i.e., does not hide the keyboard when clicking on the button. Here is another variation of InputManager I used:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
I also tried this:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
and this does not work either (keyboard isn't hidden on clicking button).
I have also tried:
<activity android:name=".AddActivity"
android:label="#string/app_name"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
and
<activity android:name=".AddActivity"
android:label="#string/app_name"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
With this one, my app stopped working:
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
This one totally hid the keyboard (the keyboard did not appear even when the editText was clicked):
text1.setInputType(InputType.TYPE_NULL);
text2.setInputType(InputType.TYPE_NULL);
I decided to use an onclicklistener for my button, instead of using another function and calling it via onClick in AddActivity.xml.
I was halfway through my question when I decided to try using OnCliCkListener once again. After several random tries, the following is the final code that works for me:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
Another way is to use OnClickListener in the following manner:
private View.OnClickListener mListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
//public void onClick(View v) {
try {
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Important points for beginners like me:
The above code should be placed before protected void onCreate(Bundle savedInstanceState)
To call the above, place this code in protected void onCreate(Bundle savedInstanceState):
btn.setOnClickListener(mListener);
Use try-catch for exception handling in both methods (onClickListener, setOnClickListener)
Upon searching for why onClick, the XML attribute doesn't work for me, while OnClickListener does, I have found the following links useful:
setOnclickListener vs OnClickListener vs View.OnClickListener
Android onClick in XML vs. OnClickListener
How exactly does the android:onClick XML attribute differ from setOnClickListener?
Difference between OnClick() event and OnClickListener?
Now, halfway through my answer, I realized my mistake in using the onClick from XML. Here is what I did to get rid of the OnClickListeners:
First, I moved the part of my code which hid the keyboard into the method in onClick. Here in my case, I moved the entire code inside hideKeyboard() to addNewTask.
Some important points regarding using onClick
The method should be public and void.
It should take a View parameter, such as View V.
Finally, the code that works:
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1, s2);
loadDataInAdd();
// hideKeyboard(); below is the code to hide keyboard
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
Summary
I found 3 ways to hide soft keyboard for my case, using:
OnClickListener :
private View.OnClickListener mListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
//public void onClick(View v) {
try {
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
setOnClickListener:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
onClick, the XML attribute:
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1, s2);
loadDataInAdd();
// hideKeyboard();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
this will help you to hide your keyboard on startup until you touch the edit text.
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
in your case, try this
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
});
Check this out
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Close/hide the Android Soft Keyboard

Android´s keyboard doesn´t appear

I have a problem with android´s keyboard. I have a fragment who has an EditText in the top of the screen and below has a nested fragment that is a QR scanner. When I click on the EditText to write something the keyboard doesn´t appear if I don´t do a long click to my device´s menu button. I am trying to show programatically when I focus the EditText but I´m not able. Here is my code, thank you in advance.
EditText caja_edicion =(EditText) getActivity().findViewById(R.id.textcodigo);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(caja_edicion, InputMethodManager.SHOW_IMPLICIT);
try adding this:
caja_edicion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(caja_edicion, InputMethodManager.SHOW_FORCED);
} else {
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(caja_edicion.getWindowToken(), 0);
}
}
});
I have change to this because I am in fragment but it doesn´t work and I don´t know why:
final EditText caja_edicion =(EditText) getActivity().findViewById(R.id.textcodigo);
caja_edicion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(caja_edicion, InputMethodManager.SHOW_FORCED);
} else {
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(caja_edicion.getWindowToken(), 0);
}
}
});

Hide keypad in android while touching outside Edit Text Area

I know that the code for dismiss tyhe keypad in android is
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
Can anyone suggest me a method to hide the keypad if we touch the area outside the text area other than the keypad in the screen.
Code to dismiss Softkeyboard is below:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
You can put it in Utility Class or if you are defining it within an activity, avoid the activity parameter, or call hideSoftKeyboard(this).
You can write a method that iterates through every View in your activity, and check if it is an instanceof EditText if it is not register a setOnTouchListener to that component and everything will fall in place. In case you are wondering how to do that, it is in fact quite simple. Here is what you do, you write a recursive method like the following.
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard();
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
Call this method after SetcontentView() with paramet as id of your view like:
RelativeLayoutPanel android:id="#+id/parent"> ... </RelativeLayout>
Then call setupUI(findViewById(R.id.parent))
Best way you can use is DONE button besides EditText make your onClickListener to do like,
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
}
});
This may be old but I got this working by implenting a custom class
public class DismissKeyboardListener implements OnClickListener {
Activity mAct;
public DismissKeyboardListener(Activity act) {
this.mAct = act;
}
#Override
public void onClick(View v) {
if ( v instanceof ViewGroup ) {
hideSoftKeyboard( this.mAct );
}
}
}
public void hideSoftKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
the best practice here is to create a Helper class and every container Relative / Linear Layouts should implement this.
**** Take note only the main Container should implement this class (For optimization) ****
and implement it like this :
Parent.setOnClickListener( new DismissKeyboardListener(this) );
the keyword this is for Activity. so if you are on fragment you use it like getActivity();
---thumbs up if it help you... --- cheers Ralph ---

Android: Dialog box show soft keyboard automatically when focus is on an EditText not working

Android: show soft keyboard automatically when focus is on an EditText
I've read this post that automatically shows the virtual keyboard when a dialog box is shown. however, it's not working for me. any ideas why? eventhough the edit text is automatically on focus when the dialogbox appear, the event doesn't trigger. I've also read the onpostresume answer but I don't know how to apply it. any help is appreciated.
final Dialog dialog = new Dialog(ThesisI.this);
dialog.setContentView(R.layout.budget_dialog);
final EditText et = (EditText) dialog.findViewById(R.id.textComments);
final Button enter = (Button) dialog.findViewById(R.id.buttonEnter);
final Button cancel = (Button) dialog.findViewById(R.id.buttonCancel);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
/**cancel */
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.show();
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
however, i noticed that if I change focus to the button then focus again to the edit text. this event works, using this code below.
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);
}
}
});
any idea on how to apply it?
What you can do is try using postDelayed(Runnable) for EditText as below,
ettext.requestFocus();
ettext.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(ettext, 0);
}
},200);
Just try adding the below line before "et.setOnFocusChangeListener"
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.showSoftInput(et, 2);

Categories

Resources