EditText request focus not working - android

I have an EditText and a Button. On click of the button i want to open the EditText keyboard and at the same time request focus on the EditText, So that the user directly start typing in the keyboard and text appears in the EditText.
But in my case when i click the button it open the keyboard, but it won't set focus on the EditText, because of which user has to click the EditText again to write on it. What is the issue. Any help or suggestion.
Code On click of button
m_SearchEditText.requestFocus();
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(m_SearchEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);

ensure that the edittext is focusable in touch mode. You can do it two way.
In xml:
android:focusableInTouchMode="true"
in Java:
view.setFocusableInTouchMode(true);
Personally I don't trust the XML definition of this param. I always request focus by these two lines of code:
view.setFocusableInTouchMode(true);
view.requestFocus();
The keyboard shoul appear on itself without the need to call InputMethodManager.
It works in most of the cases. Once it did not work for me because I have lost the reference to the object due to quite heavy processing - ensure that this is not your issue.

In my case it worked by adding a handler after you clicked to button and focus set in another view the focus can get back to your needed view.
just put this in your code:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
lastview.getEditText().clearFocus();
m_SearchEditText.requestFocus();
InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(mLastNameET, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
I hope it was helpful

Following saleh sereshki's answer and pauminku's comment, I'm using:
m_SearchEditText.post(new Runnable() {
#Override
public void run() {
m_SearchEditText.requestFocus();
}
});
which in Kotlin is the equivalent to:
m_SearchEditText.post { m_SearchEditText.requestFocus() }

The following works for me and should help:
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

In your manifest.xml write:
<activity android:name=".MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
And call m_SearchEditText.requestfocus() in oncreate().
OR,
Try:
if(m_SearchEditText.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

As an extension to this answer (I didn't add it as a comment because of reputation...).
If you want to reduce the delayed time to zero, use handler.post() instead.
Full code:
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
lastview.getEditText().clearFocus();
m_SearchEditText.requestFocus();
InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(mLastNameET, InputMethodManager.SHOW_IMPLICIT);
}
});

Minimalist Kotlin extension version because we should pretend these sorts of obtuse calls into system services are not necessary:
fun EditText.requestKeyboardFocus() {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

U need two xml attributes also to achieve this:
android:focusable="true"
android:focusableInTouchMode="true"
Add them to the EditText as well as the parent layouts(Any layout inside which these views are). By default these are false, so the focus is not given to the requested view.
Source: https://developer.android.com/reference/android/view/View.html#attr_android:focusable
After u show the EditText based on the checkbox selection, add the next and previous focus points dynamically in code.
Hope this helps.

to focus you can use this function
editText.requestFocus()
you can have two different problems with EditText. one is EditText will be focused but the keyboard is not going to open, so as other answers said, you have to open the keyboard manually. other problem is EditText not gonna focused at all means nothing happened.
for opening keyboard you can do this after requestFocus :
val manager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
manager?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
if EditText not focused at all check for this properties. EditText has to be focusable, visible, enable, focusableInTouchMode. enable all of them before calling requestFocus.
this.isFocusable = true
this.isFocusableInTouchMode = true
this.visibility = View.VISIBLE
this.isEnabled = true
and at the end you can use this kotlin extention to do all of this for you :
fun EditText.focus() {
this.isFocusable = true
this.isFocusableInTouchMode = true
this.visibility = View.VISIBLE
this.isEnabled = true
this.isCursorVisible = true
this.post {
(this.context as? Activity)?.runOnUiThread {
this.requestFocus()
val manager =
this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
manager?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
}

In my case none of the answers above worked (they don't work in Nox, for example). To set focus to EditText, you could trick it into thinking that the user actually clicked it.
So I use MotionEvent, like this:
// simulate a click, which consists of ACTION_DOWN and ACTION_UP
MotionEvent eventDown = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0);
editText.dispatchTouchEvent(eventDown);
eventDown.recycle();
MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0);
editText.dispatchTouchEvent(eventUp);
eventUp.recycle();
// To be on the safe side, also use another method
editText.setFocusableInTouchMode(true);
editText.requestFocus();
editText.requestFocusFromTouch();

The above solutions will work if the EditText is enabled.
In my code, I have disabled the view at one point and trying to request focus later without enabling.
If none of the above worked, enable the EditText and then proceed with the above solutions.
In my case it is like,
etpalletId.isEnabled = true
etpalletId.text!!.clear()
etpalletId.requestFocus()
etpalletId.isCursorVisible = true

I was combining some answers and found the following solution:
fun Fragment.focusEditText(editText: EditText) {
Timer("Timer", false).schedule(50) {
requireActivity().runOnUiThread(java.lang.Runnable {
editText.isFocusableInTouchMode = true
editText.requestFocus()
val manager =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
})
}
The timer delay makes sure that the focus request is working and the keyboard is opened manually because it did not work implicitely for me.

For some special cases in my code I do this:
later {
showKeyboard()
titleEdit.requestFocus()
}
In normal code it should look like this:
view.post {
(view.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
InputMethodManager.HIDE_IMPLICIT_ONLY)
titleEdit.requestFocus()
}
Explanation: Looks like in some cases toggleSoftInput is the only way but somehow it steal focus and it works in some case just in code tun after things gets initialized so has to be post for later execution.

Make sure that your view is focusable if not then set it to focusable:
yourView.setFocusable(true);
yourView.setFocusableInTouchMode(true);
After that set focus as follows:
yourView.requestFocus()
If that doesn't work then use this:
yourView.post(new Runnable() {
#Override
public void run() {
yourView.requestFocus();
}
});
This will work, the reason behind this is the whole UI isn't loaded in order to set the focus on a specific UI element. In this cases, the focus can be overwritten by the system that might ignore your explicit request.
So if you request the focus using a background thread (yes, I’m meaning using Thread or Runnable class) it should do the trick.
For more info visit this link:
https://medium.com/#saishaddai/til-requestfocus-not-working-22760b417cf9

It's working for request focus when sometime request focus not working
fun EditText.focus(activity: Activity) {
this.isFocusable = true
this.isFocusableInTouchMode = true
this.visibility = View.VISIBLE
this.isEnabled = true
this.isCursorVisible = true
this.post {
activity?.runOnUiThread {
this.requestFocus()
val manager =
this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
manager?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}

Related

programically click EditText

I would like to programmatically click an editText once a button has been pressed.
When a radio button "pitot_area" is selected, I want the editText associated with this selection to be programmatically clicked, so the user has one less "click" on the screen and it happens automatically.
So far I have tried
performClick()
callOnClick()
requestFocus()
the area i would like this code to be within is below:
root.pitot_area.setOnClickListener {
setAreaLabels(root)
evNodeItem.kvParams = false
evNodeItem.PitotRectArea = false
evNodeItem.PitotRoundArea = false
evNodeItem.areaParams = true
root.area_edit_text.requestFocus()
another method I have tried is
root.area_edit_text.setFocusableInTouchMode(true);
root.area_edit_text.setFocusable(true);
root.area_edit_text.requestFocus();
for the above lines of code, I have in the .xml file for the editText
android:focusable="false"
android:focusedByDefault="false"
An error does not show and the code builds, it seems this code is not read in kotlin? Does anyone have any ideas on how to do this? Thanks!
edit
ive looked at-> Focus Edit Text Programmatically (Kotlin) question sugggested below and was unable to implement it for my code.
To set direct focus to the EditText you have to open keyboard after setting focus to the EditText.
write this lines into your button click:
For Activity:
button.setOnClickListener {
editText.isFocusableInTouchMode = true
editText.requestFocus()
val inputMethodManager: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInputFromWindow(llMainView.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0)
}
For Fragment:
button.setOnClickListener {
editText.isFocusableInTouchMode = true
editText.requestFocus()
val inputMethodManager: InputMethodManager = activity!!.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInputFromWindow(llMainView.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0)
}

Set the button to Done instead of Go in EditText

I'm trying to switch the button in the softkey from "Go" to "Done" and vice-versa.
If I just set the imeoption
private fun showDoneOnSoftKeyboard() {
setImeOptionsOnSoftKeyboard(EditorInfo.IME_ACTION_DONE)
}
private fun showGoOnSoftKeyboard() {
setImeOptionsOnSoftKeyboard(EditorInfo.IME_ACTION_GO)
}
private fun setImeOptionsOnSoftKeyboard(imeOptions: Int) {
contractIdInput.imeOptions = imeOptions
}
the button is not changed. I've found that by doing:
private fun setImeOptionsOnSoftKeyboard(imeOptions: Int) {
val inputType = contractIdInput.inputType
contractIdInput.inputType = InputType.TYPE_NULL
contractIdInput.imeOptions = imeOptions
contractIdInput.inputType = inputType
}
the button is changed. The problem is though that the keyboard settings are reset that means that if I have for example the capslock set after I switch between states (for example from Done to Go) then the capslock is reset.
I have also tried
contractIdInput.imeOptions = imeOptions
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.restartInput(contractIdInput)
but this has the same effect.
I tried this one as well:
contractIdInput.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER)
but it does not work either.
Is there any other way to do the same?
It looks like this can't be done. The IME-options are thought to be set statically in the XML or programmatically but they can't be modified dynamically while the user is typing.

Is there any way to prevent a keyboard to show up in android

My activity has a single text field, which is editable, I want it so that when the activity is started the keyboard doesn't automatically start up, it should come up only when the user clicks on the editTiext field.
Any help?
In your manifest file add this line android:windowSoftInputMode="stateHidden"to your activity!
It seems like when your activity starts your TextView (since you said text field I suppose you have a TextView but the property exists on other views as well) receives automatically focus. Try looking at the TextView properties to find one that is about the object receiving focus.
public static void hideKeyboard(Context mContext){
//Hide a keypad write down on onCreate
((Activity) mContext).getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public static void showKeyboard(Context mContext,EditText edittext){
//Show a Keyboard when you click on Edittext
InputMethodManager mgr = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(edittext, InputMethodManager.SHOW_FORCED);
}

How to remove focus without setting focus to another control?

I like my UIs to be intuitive; each screen should naturally and unobtrusively guide the user on to the next step in the app. Barring that, I strive to make things as confusing and confounding as possible.
Just kidding :-)
I've got three TableRows, each containing a read-only and non-focusable EditText control and then a button to its right. Each button starts the same activity but with a different argument. The user makes a selection there and the sub-activity finishes, populating the appropriate EditText with the user's selection.
It's the classic cascading values mechanism; each selection narrows the available options for the next selection, etc. Thus I'm disabling both controls on each of the next rows until the EditText on the current row contains a value.
I need to do one of two things, in this order of preference:
When a button is clicked, immediately remove focus without setting focus to a different button
Set focus to the first button when the activity starts
The problem manifests after the sub-activity returns; the button that was clicked retains focus.
Re: #1 above - There doesn't appear to be a removeFocus() method, or something similar
Re: #2 above - I can use requestFocus() to set focus to the button on the next row, and that works after the sub-activity returns, but for some reason it doesn't work in the parent activity's onCreate().
I need UI consistency in either direction--either no buttons have focus after the sub-activity finishes or each button receives focus depending on its place in the logic flow, including the very first (and only) active button prior to any selection.
Using clearFocus() didn't seem to be working for me either as you found (saw in comments to another answer), but what worked for me in the end was adding:
<LinearLayout
android:id="#+id/my_layout"
android:focusable="true"
android:focusableInTouchMode="true" ...>
to my very top level Layout View (a linear layout). To remove focus from all Buttons/EditTexts etc, you can then just do
LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.my_layout);
myLayout.requestFocus();
Requesting focus did nothing unless I set the view to be focusable.
Old question, but I came across it when I had a similar issue and thought I'd share what I ended up doing.
The view that gained focus was different each time so I used the very generic:
View current = getCurrentFocus();
if (current != null) current.clearFocus();
You can use View.clearFocus().
Use View.requestFocus() called from onResume().
android:descendantFocusability="beforeDescendants"
using the following in the activity with some layout options below seemed to work as desired.
getWindow().getDecorView().findViewById(android.R.id.content).clearFocus();
in connection with the following parameters on the root view.
<?xml
android:focusable="true"
android:focusableInTouchMode="true"
android:descendantFocusability="beforeDescendants" />
https://developer.android.com/reference/android/view/ViewGroup#attr_android:descendantFocusability
Answer thanks to:
https://forums.xamarin.com/discussion/1856/how-to-disable-auto-focus-on-edit-text
About windowSoftInputMode
There's yet another point of contention to be aware of. By default,
Android will automatically assign initial focus to the first EditText
or focusable control in your Activity. It naturally follows that the
InputMethod (typically the soft keyboard) will respond to the focus
event by showing itself. The windowSoftInputMode attribute in
AndroidManifest.xml, when set to stateAlwaysHidden, instructs the
keyboard to ignore this automatically-assigned initial focus.
<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
great reference
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/ll_root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
LinearLayout llRootView = findViewBindId(R.id.ll_root_view);
llRootView.clearFocus();
I use this when already finished update profile info and remove all focus from EditText in my layout
====> Update: In parent layout content my EditText add line:
android:focusableInTouchMode="true"
What about just adding android:windowSoftInputMode="stateHidden" on your activity in the manifest.
Taken from a smart man commenting on this: https://stackoverflow.com/a/2059394/956975
I tried to disable and enable focusability for view and it worked for me (focus was reset):
focusedView.setFocusable(false);
focusedView.setFocusableInTouchMode(false);
focusedView.setFocusable(true);
focusedView.setFocusableInTouchMode(true);
First of all, it will 100% work........
Create onResume() method.
Inside this onResume() find the view which is focusing again and again by findViewById().
Inside this onResume() set requestFocus() to this view.
Inside this onResume() set clearFocus to this view.
Go in xml of same layout and find that top view which you want to be focused and set focusable true and focusableInTuch true.
Inside this onResume() find the above top view by findViewById
Inside this onResume() set requestFocus() to this view at the last.
And now enjoy......
android:focusableInTouchMode="true"
android:focusable="true"
android:clickable="true"
Add them to your ViewGroup that includes your EditTextView.
It works properly to my Constraint Layout. Hope this help
You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });
The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.
Please note this is pseudo-code and non-tested, but it's a possible direction you could try.
You do not need to clear focus, just add this code where you want to focus
time_statusTV.setFocusable(true);
time_statusTV.requestFocus();
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput( time_statusTV, 0);
Try the following (calling clearAllEditTextFocuses();)
private final boolean clearAllEditTextFocuses() {
View v = getCurrentFocus();
if(v instanceof EditText) {
final FocusedEditTextItems list = new FocusedEditTextItems();
list.addAndClearFocus((EditText) v);
//Focus von allen EditTexten entfernen
boolean repeat = true;
do {
v = getCurrentFocus();
if(v instanceof EditText) {
if(list.containsView(v))
repeat = false;
else list.addAndClearFocus((EditText) v);
} else repeat = false;
} while(repeat);
final boolean result = !(v instanceof EditText);
//Focus wieder setzen
list.reset();
return result;
} else return false;
}
private final static class FocusedEditTextItem {
private final boolean focusable;
private final boolean focusableInTouchMode;
#NonNull
private final EditText editText;
private FocusedEditTextItem(final #NonNull EditText v) {
editText = v;
focusable = v.isFocusable();
focusableInTouchMode = v.isFocusableInTouchMode();
}
private final void clearFocus() {
if(focusable)
editText.setFocusable(false);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(false);
editText.clearFocus();
}
private final void reset() {
if(focusable)
editText.setFocusable(true);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(true);
}
}
private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {
private final void addAndClearFocus(final #NonNull EditText v) {
final FocusedEditTextItem item = new FocusedEditTextItem(v);
add(item);
item.clearFocus();
}
private final boolean containsView(final #NonNull View v) {
boolean result = false;
for(FocusedEditTextItem item: this) {
if(item.editText == v) {
result = true;
break;
}
}
return result;
}
private final void reset() {
for(FocusedEditTextItem item: this)
item.reset();
}
}

Android show softkeyboard with showSoftInput is not working?

I have created a trivial application to test the following functionality. When my activity launches, it needs to be launched with the softkeyboard open.
My code does not work?!
I have tried various "state" settings in the manifest and different flags in the code to the InputMethodManager (imm).
I have included the setting in the AndroidManifest.xml and explicitly invoked in the onCreate of the only activity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.android.studyIme"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".StudyImeActivity"
android:label="#string/app_name"
android:windowSoftInputMode="stateAlwaysVisible">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
... the main layout (main.xml) ...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<EditText
android:id="#+id/edit_sample_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/hello"
android:inputType="textShortMessage"
/>
</LinearLayout>
... and the code ...
public class StudyImeActivity extends Activity {
private EditText mEditTextStudy;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mEditTextStudy = (EditText) findViewById(R.id.edit_study);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditTextStudy, InputMethodManager.SHOW_FORCED);
}
}
When the activity launches It seems that the keyboard is initially displayed but hidden by something else, because the following works (but is actually a dirty work-around):
First Method
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
editText.postDelayed(new Runnable()
{
#Override
public void run()
{
editText.requestFocus();
imm.showSoftInput(editText, 0);
}
}, 100);
Second method
in onCreate to launch it on activity create
new Handler().postDelayed(new Runnable() {
#Override
public void run()
{
// InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// inputMethodManager.toggleSoftInputFromWindow(EnterYourViewHere.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
if (inputMethodManager != null)
{
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
}
}, 200);
Third Method
ADD given code to activity tag in Manifest. It will show keyboard on launch, and set the first focus to your desire view.
android:windowSoftInputMode="stateVisible"
Hey I hope you are still looking for the answer as I found it when testing out my code. here is the code:
InputMethodManager imm = (InputMethodManager)_context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, 0);
Here is my question that was answered:
android - show soft keyboard on demand
This worked with me on a phone with hard keyboard:
editText1.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
This is so subtle, that it is criminal. This works on the phones that do NOT have a hard, slide-out keyboard. The phones with a hard keyboard will not open automatically with this call. My LG and old Nexus One do not have a keyboard -- therefore, the soft-keyboard opens when the activity launches (that is what I want), but the MyTouch and HTC G2 phones that have slide-out keyboards do not open the soft keyboard until I touch the edit field with the hard keyboard closed.
This answer maybe late but it works perfectly for me. Maybe it helps someone :)
public void showSoftKeyboard(View view) {
if (view.requestFocus()) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
boolean isShowing = imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
if (!isShowing)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
}
Depends on you need, you can use other flags
InputMethodManager.SHOW_FORCED
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Showing Soft Keyboard is a big problem. I searched a lot to come to a final conclusion. Thanks to this answer which gave a number of clues: https://stackoverflow.com/a/16882749/5903344
Problem:
Normally we call showSoftInput as soon as we initialize the views. In Activities, this is mostly in onCreate, in Fragments onCreateView. In order to show the keyboard, IMM needs to have the focsedView as active. This can be checked using isActive(view) method of IMM. If we call showSoftInput while the views are being created, there is a good chance that the view won't be active for IMM. That is the reason why sometimes a 50-100 ms delayed showSoftInput is useful. However, that still does not guarantee that after 100 ms the view will become active. So in my understanding, this is again a hack.
Solution:
I use the following class. This keeps running every 100 ms until the keyboard has been successfully shown. It performs various checks in each iteration. Some checks can stop the runnable, some post it after 100 ms.
public class KeyboardRunnable extends Runnable
{
// ----------------------- Constants ----------------------- //
private static final String TAG = "KEYBOARD_RUNNABLE";
// Runnable Interval
private static final int INTERVAL_MS = 100;
// ----------------------- Classes ---------------------------//
// ----------------------- Interfaces ----------------------- //
// ----------------------- Globals ----------------------- //
private Activity parentActivity = null;
private View targetView = null;
// ----------------------- Constructor ----------------------- //
public KeyboardRunnable(Activity parentActivity, View targetView)
{
this.parentActivity = parentActivity;
this.targetView = targetView;
}
// ----------------------- Overrides ----------------------- //
#Override
public void run()
{
// Validate Params
if ((parentActivity == null) || (targetView == null))
{
Dbg.error(TAG, "Invalid Params");
return;
}
// Get Input Method Manager
InputMethodManager imm = (InputMethodManager) parentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
// Check view is focusable
if (!(targetView.isFocusable() && targetView.isFocusableInTouchMode()))
{
Dbg.error(TAG, "Non focusable view");
return;
}
// Try focusing
else if (!targetView.requestFocus())
{
Dbg.error(TAG, "Cannot focus on view");
Post();
}
// Check if Imm is active with this view
else if (!imm.isActive(targetView))
{
Dbg.error(TAG, "IMM is not active");
Post();
}
// Show Keyboard
else if (!imm.showSoftInput(targetView, InputMethodManager.SHOW_IMPLICIT))
{
Dbg.error(TAG, "Unable to show keyboard");
Post();
}
}
// ----------------------- Public APIs ----------------------- //
public static void Hide(Activity parentActivity)
{
if (parentActivity != null)
{
InputMethodManager imm = (InputMethodManager) parentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(parentActivity.findViewById(android.R.id.content).getWindowToken(), 0);
}
else
{
Dbg.error(TAG, "Invalid params to hide keyboard");
}
}
// ----------------------- Private APIs ----------------------- //
protected void Post()
{
// Post this aftr 100 ms
handler.postDelayed(this, INTERVAL_MS);
}
}
To use this, Just create an instance of this class. Pass it the parent activity and the targetView which would have keyboard input and focus afterwards. Then post the instance using a Handler.
Following worked for me:
mEditTextStudy.requestFocus();
mEditTextStudy.post(
new Runnable() {
#Override
public void run() {
InputMethodManager imm =
(InputMethodManager)
getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(mEditTextStudy, SHOW_FORCED);
}
}
});
For those who want a less hacky, and as-short-as-it-gets reliable solution to show the keyboard in 2022, I found this blog Showing the Android Keyboard Reliably with an answer that works really well for me, and it is less hacky than the postDelay 100ms as it utilizes OnWindowFocusChangeListener to do the trick.
It is really simple to use (something like this should be built in By Google!):
editText.focusAndShowKeyboard()
Add this extension method in Kotlin to use this on any View!
fun View.focusAndShowKeyboard() {
/**
* This is to be called when the window already has focus.
*/
fun View.showTheKeyboardNow() {
if (isFocused) {
post {
// We still post the call, just in case we are being notified of the windows focus
// but InputMethodManager didn't get properly setup yet.
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
requestFocus()
if (hasWindowFocus()) {
// No need to wait for the window to get focus.
showTheKeyboardNow()
} else {
// We need to wait until the window gets focus.
viewTreeObserver.addOnWindowFocusChangeListener(
object : ViewTreeObserver.OnWindowFocusChangeListener {
override fun onWindowFocusChanged(hasFocus: Boolean) {
// This notification will arrive just before the InputMethodManager gets set up.
if (hasFocus) {
this#focusAndShowKeyboard.showTheKeyboardNow()
// It’s very important to remove this listener once we are done.
viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
}
})
}
}
You may think but why all these code when calling showSoftInput works during my testing? What I think it works for some people but not for others is because most people tested that in a normal activity or fragment, while the ones who reported not working (like me) were probably testing it in a dialog fragment or some sort. So this solution is more fool proof and can be used anywhere.
My code had the toggle in it but not postDelayed. I had tried postDelayed for the showSoftInput without success and I have since tried your suggested solution. I was about to discard it as yet another failed potential solution until I decided to increase the delay time. It works for me all the way down to 200 ms at which point it doesn't work, at least not on the physical phones. So before you poor android developers ditch this answer, try upping the delay for a successful solution. It may pay to add a bit for older slower phones. Thanks heaps, was working on this one for hours.
Solution for Xamarin developers (_digit1 == EditText):
var focussed = _digit1.RequestFocus();
if (focussed)
{
Window.SetSoftInputMode(SoftInput.StateAlwaysVisible);
var imm = (InputMethodManager)GetSystemService(InputMethodService);
imm.ToggleSoftInput(ShowFlags.Forced, 0);
}
Here is the modified version of Siddharth Garg's answer. It work's 100% of the time.
import android.content.Context;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class SoftInputService implements Runnable {
private static final String TAG = SoftInputService.class.getSimpleName();
private static final int INTERVAL_MS = 100;
private Context context;
private View targetView;
private Handler handler;
public SoftInputService(Context context, View targetView) {
this.context = context;
this.targetView = targetView;
handler = new Handler(Looper.getMainLooper());
}
#Override
public void run() {
if (context == null || targetView == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!targetView.isFocusable() || !targetView.isFocusableInTouchMode()) {
Log.d(TAG,"focusable = " + targetView.isFocusable() + ", focusableInTouchMode = " + targetView.isFocusableInTouchMode());
return;
} else if (!targetView.requestFocus()) {
Log.d(TAG,"Cannot focus on view");
post();
} else if (!imm.showSoftInput(targetView, InputMethodManager.SHOW_IMPLICIT)) {
Log.d(TAG,"Unable to show keyboard");
post();
}
}
public void show() {
handler.post(this);
}
public static void hide(Context context, IBinder windowToekn) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(windowToekn, 0);
}
protected void post() {
handler.postDelayed(this, INTERVAL_MS);
}
}
Usage:
// To show the soft input
new SoftInputService(context, theEditText).show();
// To hide the soft input
SoftInputService.hide(context, theEditText.getWindowToken());
Similar problem but different solution so posting in case it is useful to others.
The problem was not with my code and use of:
inputMethodManager.showSoftInput(kbdInput, InputMethodManager.SHOW_IMPLICIT);
The problem related to that as of more recent sdk compiling. I'm no longer able to apply the above to a field that is hidden. Seems you must have your field visible and larger than 0 now for keyboard to appear. I was doing this because my app is more of a game using the keyboard as entry against an image. So all I had to do was change:
<EditText
android:id="#+id/kb_input"
android:layout_width="0dp"
android:layout_height="0dp"
/>
to
<EditText
android:id="#+id/kb_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textColorHighlight="#color/black"
android:backgroundTint="#color/black"
android:cursorVisible="false"
/>
My background was black so while the EditText is now visible it looks invisible on the black background.
This works for me:
public void requestFocusAndShowSoftInput(View view){
view.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
If you're trying to show the soft keyboard in a Fragment, you need to wait until the Activity has been created before calling showSoftInput(). Sample code:
public class SampleFragment extends Fragment {
private InputMethodManager mImm;
private TextView mTextView;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mImm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
showSoftKeyboard(mTextView);
}
/**
* Request the InputMethodManager show the soft keyboard. Call this in {#link #onActivityCreated(Bundle)}.
* #param view the View which would like to receive text input from the soft keyboard
*/
public void showSoftKeyboard(View view) {
if (view.requestFocus()) {
mImm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
}
Removing android:windowSoftInputMode from the manifest solved my problem!
in my case, i solved this problem putting this code in onResume simply:
override fun onResume() {
super.onResume()
binding.edittext.requestFocus()
val imm =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(binding.edittext, InputMethodManager.SHOW_IMPLICIT)
}

Categories

Resources