I want to hide keyboard after clicking on EditText in android i tried below code but its not working.
mPassword.setInputType(InputType.TYPE_CLASS_NUMBER);
mPassword.requestFocus();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(mPassword, InputMethodManager.RESULT_HIDDEN);
I have also given android:windowSoftInputMode="stateHidden" in activity manifest.
still i'm getting keyboard.Please tell me how can i hide soft keyboard??
You can use the following code to hide the soft keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mPassword.getWindowToken(), 0);
Also,
If you want to hide when the activity starts, then edit your manifest file as
<activity android:name="com.your.package.ActivityName"
android:windowSoftInputMode="stateHidden" />
Use following code in your manifest file.
<activity
android:name="YourActivity"
android:configChanges="keyboardHidden"
android:windowSoftInputMode="stateHidden"/>
Try like this,
your_edittext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (m != null) {
m.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
your_edittext.clearFocus();
}
}
});
Here's the solution which will hide the keyboard from anywhere.
1st create in your activity of choice the listener for the state and the method that will do the closing (based on the open state).
public class MainActivity extends SherlockFragmentActivity {
private boolean mKeyboardOpen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// add "keyboard open listener"
final View v = findViewById(R.id.pager);
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int hRoot = v.getRootView().getHeight();
int hView = v.getHeight();
int heightDiff = hRoot - hView;
// if more than 150 pixels, its probably a keyboard...
mKeyboardOpen = heightDiff > 150;
Log.d(TAG, "hRoot=" + hRoot + ", hView=" + hView + ", mKeyboardOpen=" + mKeyboardOpen);
}
});
}
public void closeSoftKeyboard() {
if (mKeyboardOpen) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
}
2nd call ((MainActivity) getActivity()).closeSoftKeyboard(); from anywhere, e.g. your EditText's OnClickListener().
Hint: I'm using the ViewPager root view (R.id.pager), but you should probably replace it with your view root id.
Related
I have an EdiText in my project developed on android studio .
android:id="#+id/Number"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textSize="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
I need to find a way to disable the keyboard when I click on the edit text, meaning that when I click on the EditText the keyboard should not open .
Just disable it.
EditText et = (EditText) findViewById(R.id.edittext);
et.setEnabled(false);
OR
Add android:inputType="none" in your xml
Do it this way
final EditText editText = findViewById(R.id.Number);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
here you go.
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);
}
}
In your code you need to do it programmatically this way: declare a global variable for InputMethodManager:
private InputMethodManager im ;
In onCreate() method define it:
im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(youredittext.getWindowToken(), 0);
Set the onClickListener to that edit text inside onCreate():
youredittext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
im.showSoftInput(youredittext, InputMethodManager.SHOW_IMPLICIT);
}
});
This will work.
If you want to prevent user to edit text then you may use android:enabled="false" property in edittext
I found a number of answers to this question but none of them are working for me. I have an Edit text in my Fragment, which gets launched when the application starts. When this Fragment opens, the soft keyboard pops up as well. How do I prevent that from happening? This is what I have in my onCreateView method in my Fragment....
try {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(userName.getWindowToken(), 0);
}catch(Exception e) {
e.printStackTrace();
}
Try this in onCreateView or onActivityCreated.
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
My recently project I use the code as follow to hide the keyboard layout, maybe you can try it.(I learn it from the source code of Wordpress-android)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_template_add_doc, container, false);
//hide the keyboard if it is visible
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
return view;
}
Try the below logics to hide the keyboard from opening automatically.
Try to place your edit text in a separate linearlayout and set android:focusableInTouchMode="true". This will automatically avoids the keyboard opening automatically.
<LinearLayout
android:id = "#+id/layout"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:focusable = "true"
android:focusableInTouchMode = "true">
<EditText
android:id = "#+id/edit_text"
android:layout_width = "match_content"
android:layout_height = "wrap_content"/>
</LinearLayout>
or if the above fails, hide Programmatically by using the code below. Write it as a separate function and call it in the code.
call this method in your fragment after view is created as below.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
hideKeyboard();
}
public void hideKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus()
.getWindowToken(), 0);
} // hideKeyboard
Good Luck..!
This worked for me,try this way
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
hideKeyboard(getActivity());
}
public static void hideKeyboard( Context context ) {
try {
InputMethodManager inputManager = ( InputMethodManager ) context.getSystemService( Context.INPUT_METHOD_SERVICE );
View view = ( (Activity) context ).getCurrentFocus();
if ( view != null ) {
inputManager.hideSoftInputFromWindow( view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS );
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:background="#color/background_listview"
android:orientation="vertical">
Using this in Main upper Layout
set focusable true and android:focusableInTouchMode true
android:focusable="true"
android:focusableInTouchMode="true"
You can also add this line in AndroidManifest.xml to your fragment activity.
line to add:-
android:windowSoftInputMode="stateHidden|adjustResize"
see code snippet below:-
<activity android:name=".activity.FragmentActivity"
android:windowSoftInputMode="stateHidden|adjustResize"/>
Below is working in Kotlin
private fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
private fun Context.hideKeyboard(view: View) {
val inputMethodManager =
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
private fun Fragment.showKeyboard(et: EditText) {
view?.let { activity?.showKeyboard(et) }
}
private fun Context.showKeyboard(et: EditText) {
et.requestFocus()
et.setSelection(et.length()) // This line use to always put cursor at the end of line.
val inputMethodManager =`enter code here`
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(et, 0)
}
I create android app with xamarin + mvvmcross. I have an MvxAutoCompleteTextView in my MvxFragment. After writing in the MvxAutoCompleteTextView and clicking on the others controls, I want to hide the virtual keyboard. I use this code
public class MyFragment : MvxFragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
var view = this.BindingInflate(Resource.Layout.frMy, null);
var autoComplete = view.FindViewById<MvxAutoCompleteTextView>(Resource.Id.acMy);
InputMethodManager inputManager = (InputMethodManager)inflater.Context.GetSystemService(Context.InputMethodService);
inputManager.HideSoftInputFromWindow(autoComplete.WindowToken, HideSoftInputFlags.None);
return view;
}
}
but this not work. How do I hide the keyboard?
You can hide the soft keyboard giving focus to something that is not a "keyboard launcher" control, for example, the parent container of your auto-complete control.
parentContainer = FindViewById<LinearLayout>(Resource.Id.parentContainer);
parentContainer.RequestFocus();
Let´s say your parent container is a LinearLayout, you should allow it to get focus with these 2 properties:
<LinearLayout
android:id="#+id/parentContainer"
android:focusable="true"
android:focusableInTouchMode="true">
I got the answer in java from here : https://stackoverflow.com/a/28939113/4664754
Here is the C# version (tested and working):
public override bool DispatchTouchEvent(MotionEvent ev)
{
if (ev.Action == MotionEventActions.Down)
{
View v = CurrentFocus;
if (v.GetType() == typeof(EditText))
{
Rect outRect = new Rect();
v.GetGlobalVisibleRect(outRect);
if (!outRect.Contains((int)ev.RawX, (int)ev.RawY))
{
v.ClearFocus();
InputMethodManager imm = (InputMethodManager)this.GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(v.WindowToken, 0);
}
}
}
return base.DispatchTouchEvent(ev);
}
This piece of code will hide the soft keyboard if you click on anything that is not an EditText.
You just have to paste this in your activity class (for example your loginActivity)
Try this:
InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(autoComplete.WindowToken, 0);
the value 0 in HideSoftInputFromWindow is the const Android.Views.InputMethods.HideSoftInputFlags.None so you can use the equivalent syntax:
InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(autoComplete.WindowToken, Android.Views.InputMethods.HideSoftInputFlags.None);
Try my function:
public static void Close_AndroidKeyboard(Activity context){
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(
Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
Sorry but i work with android studio, tell me if I helped you and good programming!
The easiest solution I've found, is to simply call the Unfocus() method on the control with focus (for instance an Entry or Editor). You can embed this call in an UnfocusOnClicked behaviour if you want to specify the function in the XAML directly.
I have a View (Tabhost) and I want to show it when I click a button, and when I show thw Tabhost I hide the softkeyboard, and if I Tab the same button, I want to show the softkeyboard and hid the Tabhost, my cod of On click is bellow, but it did not behave as I want.. can any body help!?
public void show_smily(View view) { // event habdler
EditText composer = (EditText) findViewById(R.id.message_composer);
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
if(!tabHost.isShown()) {
imm.hideSoftInputFromWindow(composer.getWindowToken(),0);
tabHost.setVisibility(View.VISIBLE);
}
if(tabHost.isShown()) {
tabHost.setVisibility(View.GONE);
imm.showSoftInput(composer,0);
}
}
Ok I forgot to put else before the second if, so, the first codition true, and then the second will be true, the application was execute the two blocks...
public void show_smily(View view) { // event habdler
EditText composer = (EditText) findViewById(R.id.message_composer);
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
if(!tabHost.isShown()) {
imm.hideSoftInputFromWindow(composer.getWindowToken(),0);
tabHost.setVisibility(View.VISIBLE);
}
else if(tabHost.isShown()) { // here was the problem
tabHost.setVisibility(View.GONE);
imm.showSoftInput(composer,0);
}
}
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)
}