Disable keyboard on EditText - android

I'm doing a calculator.
So I made my own Buttons with numbers and functions.
The expression that has to be calculated, is in an EditText, because I want users can add numbers or functions also in the middle of the expression, so with the EditText I have the cursor. But I want to disable the Keyboard when users click on the EditText.
I found this example that it's ok for Android 2.3, but with ICS disable the Keyboard and also the cursor.
public class NoImeEditText extends EditText {
public NoImeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
return false;
}
}
And then I use this NoImeEditText in my XML file
<com.my.package.NoImeEditText
android:id="#+id/etMy"
....
/>
How I can make compatible this EditText with ICS???
Thanks.

Here is a website that will give you what you need
As a summary, it provides links to InputMethodManager and View from Android Developers. It will reference to the getWindowToken inside of View and hideSoftInputFromWindow() for InputMethodManager
A better answer is given in the link, hope this helps.
here is an example to consume the onTouch event:
editText_input_field.setOnTouchListener(otl);
private OnTouchListener otl = new OnTouchListener() {
public boolean onTouch (View v, MotionEvent event) {
return true; // the listener has consumed the event
}
};
Here is another example from the same website. This claims to work but seems like a bad idea since your EditBox is NULL it will be no longer an editor:
MyEditor.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
int inType = MyEditor.getInputType(); // backup the input type
MyEditor.setInputType(InputType.TYPE_NULL); // disable soft input
MyEditor.onTouchEvent(event); // call native handler
MyEditor.setInputType(inType); // restore input type
return true; // consume touch even
}
});
Hope this points you in the right direction

Below code is both for API >= 11 and API < 11. Cursor is still available.
/**
* Disable soft keyboard from appearing, use in conjunction with android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
* #param editText
*/
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);
}
}

You can also use setShowSoftInputOnFocus(boolean) directly on API 21+ or through reflection on API 14+:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
} else {
try {
final Method method = EditText.class.getMethod(
"setShowSoftInputOnFocus"
, new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
} catch (Exception e) {
// ignore
}
}

Add below properties to the Edittext controller in the layout file
<Edittext
android:focusableInTouchMode="true"
android:cursorVisible="false"
android:focusable="false" />
I have been using this solution for while and it works fine for me.

editText.setShowSoftInputOnFocus(false);

try: android:editable="false" or android:inputType="none"

Disable the keyboard (API 11 to current)
This is the best answer I have found so far to disable the keyboard (and I have seen a lot of them).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(false);
} else { // API 11-20
editText.setTextIsSelectable(true);
}
There is no need to use reflection or set the InputType to null.
Re-enable the keyboard
Here is how you re-enable the keyboard if needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(true);
} else { // API 11-20
editText.setTextIsSelectable(false);
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setClickable(true);
editText.setLongClickable(true);
editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
}
See this Q&A for why the complicated pre API 21 version is needed to undo setTextIsSelectable(true):
How to enable keyboard on touch after disabling it with setTextIsSelectable
This answer needs to be more thoroughly tested.
I have tested the setShowSoftInputOnFocus on higher API devices, but after #androiddeveloper's comment below, I see that this needs to be more thoroughly tested.
Here is some cut-and-paste code to help test this answer. If you can confirm that it does or doesn't work for API 11 to 20, please leave a comment. I don't have any API 11-20 devices and my emulator is having problems.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="#android:color/white">
<EditText
android:id="#+id/editText"
android:textColor="#android:color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="enable keyboard"
android:onClick="enableButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="disable keyboard"
android:onClick="disableButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
}
// when keyboard is hidden it should appear when editText is clicked
public void enableButtonClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(true);
} else { // API 11-20
editText.setTextIsSelectable(false);
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setClickable(true);
editText.setLongClickable(true);
editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
}
}
// when keyboard is hidden it shouldn't respond when editText is clicked
public void disableButtonClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(false);
} else { // API 11-20
editText.setTextIsSelectable(true);
}
}
}

Gathering solutions from multiple places here on StackOverflow, I think the next one sums it up:
If you don't need the keyboard to be shown anywhere on your activity, you can simply use the next flags which are used for dialogs (got from here) :
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
If you don't want it only for a specific EditText, you can use this (got from here) :
public static boolean disableKeyboardForEditText(#NonNull EditText editText) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
return true;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
try {
final Method method = EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
try {
Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
return false;
}
Or this (taken from here) :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
editText.setShowSoftInputOnFocus(false);
else
editText.setTextIsSelectable(true);

To add to Alex Kucherenko solution: the issue with the cursor getting disappearing after calling setInputType(0) is due to a framework bug on ICS (and JB).
The bug is documented here: https://code.google.com/p/android/issues/detail?id=27609.
To workaround this, call setRawInputType(InputType.TYPE_CLASS_TEXT) right after the setInputType call.
To stop the keyboard from appearing, just override OnTouchListener of the EditText and return true (swallowing the touch event):
ed.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
The reasons for the cursor appearing on GB devices and not on ICS+ had me tearing my hair out for a couple of hours, so I hope this saves someone's time.

I found this solution which works for me. It also places the cursor, when clicked on EditText at the correct position.
EditText editText = (EditText)findViewById(R.id.edit_mine);
// set OnTouchListener to consume the touch event
editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event); // handle the event first
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // hide the soft keyboard
}
return true;
}
});

// only if you completely want to disable keyboard for
// that particular edit text
your_edit_text = (EditText) findViewById(R.id.editText_1);
your_edit_text.setInputType(InputType.TYPE_NULL);

Just set:
NoImeEditText.setInputType(0);
or in the constructor:
public NoImeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setInputType(0);
}

This worked for me.
First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:
<activity ... android:windowSoftInputMode="stateHidden">
Then on onCreate method of youractivity, add the foloowing code:
EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethod!= null) {
inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return true;
}
});
Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".
This will make the pointer visible.
In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.

Just put this line inside the activity tag in manifest
android:windowSoftInputMode="stateHidden"

In my case, these lines work for me...
android:inputType="none"
android:focusableInTouchMode="true"
android:cursorVisible="false"
android:focusable="false"
before adding these lines, When I clicked on editText default keyboard showed/invoked.
After adding these lines keyboard was not displayed.

One way to disable keyboard on EditText is
binding.InputTextView.showSoftInputOnFocus = false

For Edit Text use the attribute android:focusable="false"

I donĀ“t know if this answer is the better, but i found a possible faster solution. On XML, just put on EditText this attributes:
android:focusable="true"
android:focusableInTouchMode="false"
And then do what you need with onClickListener.

Related

get selection handles programmatically in android

In my app I have EditText element but I use it like TextView (it is not editable).
I want to select all text in this field by click on some button.
I do it with the next code
Selection.setSelection((Spannable) et.getText(),0, et.getText().length());
et.setSelected(true);
It works fine and text selected but after that I can not change ends of selection.
How can I call selection handles programmatically?
Also I blocked OnLongClick because I need only Copy option and add it in custom button.
You need to make sure that the EditText has the property android:textIsSelectable="true" in the layout file.
You can also do the same thing by
et.setTextIsSelectable(true);
But please make sure that your application's minSdkVersion is 11 to use this.
Try some thing like this
et.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int strt= et.getSelectionStart();
int end = et.getSelectionEnd();
Log.i(" Selectionm",et.getText().toString().substring(strt, end));
return false;
}
});
With required android:textIsSelectable="true", call the following method with EditText or TextView as parameter:
private fun forceSelectionWithHandlesVisible(view: TextView) {
if (!view.hasSelection()) {
view.performLongClick()
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
// Hack required to make the selection handles visible when focus programmatically
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_UP, 0F, 0F, 0)
with(event) {
view.onTouchEvent(this)
recycle()
}
}
}
Worked for me.

Android Hide Soft Keyboard from EditText while not losing cursor

I've come about as far as this which gets me halfway there, but not quite.
I have a dialer Fragment that has all the usual Buttons to enter a number including backspace, so I don't need the soft keyboard. I'd also like to give the user the ability to paste text (long click... works fine per default), as well as to edit what has been entered so I need the cursor.
The easiest way I found to make sure the soft keyboard doesn't pop up if the user clicks inside the EditText is to set the inputType to null - but that kills the cursor as well.
So, how do I declare my EditText and what kind of commands should I launch to have my EditText field never ever show the soft keyboard no matter what the user attempts, but still retain paste functionality and the cursor?
I've also tried android:windowSoftInputMode="stateAlwaysHidden" in my manifest, but to no avail.
This worked for me:
// Update the EditText so it won't popup Android's own keyboard, since I have my own.
EditText editText = (EditText)findViewById(R.id.edit_mine);
editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return true;
}
});
I have finally found a (for me) working solution to this.
First part (in onCreate):
// Set to TYPE_NULL on all Android API versions
mText.setInputType(InputType.TYPE_NULL);
// for later than GB only
if (android.os.Build.VERSION.SDK_INT >= 11) {
// this fakes the TextView (which actually handles cursor drawing)
// into drawing the cursor even though you've disabled soft input
// with TYPE_NULL
mText.setRawInputType(InputType.TYPE_CLASS_TEXT);
}
In addition, android:textIsSelectable needs to be set to true (or set in onCreate) and the EditText must not be focused on initialization. If your EditText is the first focusable View (which it was in my case), you can work around this by putting this just above it:
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" >
<requestFocus />
</LinearLayout>
You can see the results of this in the Grapher application, free and available in Google Play.
Setting the flag textIsSelectable to true disables the soft keyboard.
You can set it in your xml layout like this:
<EditText
android:id="#+id/editText"
...
android:textIsSelectable="true"/>
Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);
The cursor will still be present, you'll be able to select/copy/cut/paste but the soft keyboard will never show.
Best solution from #Lupsaa here:
Setting the flag textIsSelectable to true disables the soft keyboard.
You can set it in your xml layout like this:
<EditText
android:id="#+id/editText"
...
android:textIsSelectable="true"/>
Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);
The cursor will still be present, you'll be able to select/copy/cut/paste but the soft keyboard will never show.
If your min SDK is 21, you can this method from java code:
editText.setShowSoftInputOnFocus(false);
Credits to Chen Su article.
use
android:windowSoftInputMode="stateHidden"
in your manifest file instead of android:windowSoftInputMode="stateAlwaysHidden"
This is what I did.
First, in manifest inside activity
android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
Second, in onCreate if inside activity or onActivityCreated if inside fragment
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideSoftKeyboard(v);
}
});
Do not forget to request focus to the editText
editText.requestFocus();
Then add the hideSoftKeyboard(v) method same as the other answer.
private void hideSoftKeyboard(View v){
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
The key here is to requestFocus before clicking the EditText. If without focus, first click will make the keyboard show up(my experience). However, this is applied if you have a single EditText in an activity. With this, you still can type with custom keyboard(if any), can copy and paste, and cursor is still visible.
The exact functionality that you require is provided by setting the flag textIsSelectable in EditText to true. With this, the cursor will still be present, and you'll be able to select/copy/cut/paste, but SoftKeyboard will never show. Requires API 11 and above.
You can set it in your xml layout like this:
<EditText
android:textIsSelectable="true"
...
/>
Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);
For anyone using API 10 and below, hack is provided here :
https://stackoverflow.com/a/20173020/7550472
This works perfectly (for me) in 2 steps:
<activity... android:windowSoftInputMode="stateHidden"> in manifest file
Add these properties in your editText XML code
android:focusable="true"
android:focusableInTouchMode="true
You have to put both 1 and 2, only then it will work.
Cheers
EditText text = (EditText) findViewById(R.id.text);
if (Build.VERSION.SDK_INT >= 11) {
text.setRawInputType(InputType.TYPE_CLASS_TEXT);
text.setTextIsSelectable(true);
} else {
text.setRawInputType(InputType.TYPE_NULL);
text.setFocusable(true);
}
First add android:windowSoftInputMode="stateHidden" in your manifest file, under the activity. like this
<activity... android:windowSoftInputMode="stateHidden">
The on your xml add this android:textIsSelectable="true" . This will make the pointer visible.
Then on onCreate method of the activity, add this:
EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethod!= null) {
inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return true;
}
});
i found this very useful code and it work as charm, it head the Keyboard totaly, but keeping cursor and you can copy past, move the cursor...ect
using :
hideSoftKeyboard(editText);
methode :
public void hideSoftKeyboard(EditText edit) {
if (android.os.Build.VERSION.SDK_INT <= 10) {
edit.setInputType(InputType.TYPE_NULL);
} else {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
Class<EditText> cls = EditText.class;
Method setSoftInputShownOnFocus;
setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
setSoftInputShownOnFocus.setAccessible(true);
setSoftInputShownOnFocus.invoke(edit, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
EditText editText = (EditText)findViewById(R.id.edit_mine);
editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return true;
}
});
ha... this is the correct way of doing...this job done... this gonna work !
You can use the following line of code in the activity's onCreate method to make sure the keyboard only pops up when a user clicks or touch into an EditText Field. I tried lots of methods and codes from stackoverflow but didnt work any but this
Works Perfectly for me!! Try this.. :)`
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
You can use the following line of code in the activity's onCreate method to make sure the keyboard only pops up when a user clicks or touch into an EditText Field. I tried lots of methods and codes from stackoverflow but didnt work any but this Works Perfectly for me!! Try this.. :)`
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

How to hide Android soft keyboard on EditText

I have an Activity with some EditText fields and some buttons as a convenience for what normally would be used to populate those fields. However when we the user touches one of the EditText fields the Android soft keyboard automatically appears. I want it to remain hidden by default, unless the user long presses the menu button. I have search for a solution to this and found several answers, but so far I can't get them to work.
I have tried the following:
1 - In the onCreate method,
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
2 - Also in the onCreate method,
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
3 - and fIn the Manifest file,
<activity android:name=".activityName" android:windowSoftInputMode="stateAlwaysHidden"/>
None of these methods work. Whenever the user clicks on the EditText field, the soft keyboard appears. I only want the soft keyboard to appear if the user explicitly shows it by long pressing the menu key.
Why isn't this working?
This will help you
editText.setInputType(InputType.TYPE_NULL);
Edit:
To show soft keyboard, you have to write following code in long key press event of menu button
editText.setInputType(InputType.TYPE_CLASS_TEXT);
editText.requestFocus();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
You need to add the following attribute for the Activity in your AndroidManifest.xml.
<activity
...
android:windowSoftInputMode="stateHidden|adjustResize"
...
/>
After long time looking into TextView class I found a way to prevent keyboard to appears. The trick is hide it right after it appears, so I searched a method that is called after keyboard appear and hide it.
Implemented EditText class
public class NoImeEditText extends EditText {
public NoImeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* This method is called before keyboard appears when text is selected.
* So just hide the keyboard
* #return
*/
#Override
public boolean onCheckIsTextEditor() {
hideKeyboard();
return super.onCheckIsTextEditor();
}
/**
* This methdod is called when text selection is changed, so hide keyboard to prevent it to appear
* #param selStart
* #param selEnd
*/
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
hideKeyboard();
}
private void hideKeyboard(){
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
and style
<com.my.app.CustomViews.NoImeEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:background="#null"
android:textSize="#dimen/cell_text" />
I sometimes use a bit of a trick to do just that. I put an invisible focus holder somewhere on the top of the layout. It would be e.g. like this
<EditText android:id="#id/editInvisibleFocusHolder"
style="#style/InvisibleFocusHolder"/>
with this style
<style name="InvisibleFocusHolder">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">0dp</item>
<item name="android:focusable">true</item>
<item name="android:focusableInTouchMode">true</item>
<item name="android:inputType">none</item>
</style>
and then in onResume I would call
editInvisibleFocusHolder.setInputType(InputType.TYPE_NULL);
editInvisibleFocusHolder.requestFocus();
That works nicely for me from 1.6 up to 4.x
My test result:
with setInputType:
editText.setInputType(InputType.TYPE_NULL);
the soft keyboard disappears, but the cursor will also disappear.
with setShowSoftInputOnFocus:
editText.setShowSoftInputOnFocus(false)
It works as expected.
The soft keyboard kept rising even though I set EditorInfo.TYPE_NULL to the view.
None of the answers worked for me, except the idea I got from nik431's answer:
editText.setCursorVisible(false);
editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
The following line is exactly what is being looked for. This method has been included with API 21, therefore it works for API 21 and above.
edittext.setShowSoftInputOnFocus(false);
There seems to be quite a variety of ways of preventing the system keyboard from appearing, both programmatically and in xml. However, this is the way that has worked for me while supporting pre API 11 devices.
// prevent system keyboard from appearing
if (android.os.Build.VERSION.SDK_INT >= 11) {
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);
} else {
editText.setRawInputType(InputType.TYPE_NULL);
editText.setFocusable(true);
}
Let's try to set the below properties in your xml for EditText
android:focusableInTouchMode="true" android:cursorVisible="false".
if you want to hide the softkeypad at launching activity please go through this link
Three ways based on the same simple instruction:
a). Results as easy as locate (1):
android:focusableInTouchMode="true"
among the configuration of any precedent element in the layout, example:
if your whole layout is composed of:
<ImageView>
<EditTextView>
<EditTextView>
<EditTextView>
then you can write the (1) among ImageView parameters and this will grab android's attention to the ImageView instead of the EditText.
b). In case you have another precedent element than an ImageView you may need to add (2) to (1) as:
android:focusable="true"
c). you can also simply create an empty element at the top of your view elements:
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px" />
This alternative until this point results as the simplest of all I've seen. Hope it helps...
Simply Use
EditText.setFocusable(false); in activity
or
use in xml
android:focusable="false"
Simply use below method
private fun hideKeyboard(activity: Activity, editText: EditText) {
editText.clearFocus()
(activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(editText.windowToken, 0)
}
weekText = (EditText) layout.findViewById(R.id.weekEditText);
weekText.setInputType(InputType.TYPE_NULL);
Hide the keyboard
editText.setInputType(InputType.TYPE_NULL);
Show Keyboard
etData.setInputType(InputType.TYPE_CLASS_TEXT);
etData.setFocusableInTouchMode(true);
in the parent layout
android:focusable="false"
public class NonKeyboardEditText extends AppCompatEditText {
public NonKeyboardEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
return false;
}
}
and add
NonKeyboardEditText.setTextIsSelectable(true);
I also faced the same problem, I fixed that via this method,
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// do something..
}
closeKeyborad();
return true;
}
return false;
}
});
Call that function before return true.
private void closeKeyborad() {
View view = this.getCurrentFocus();
if (view != null){
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken() , 0);
}
}

EditText onClickListener in Android

I want an EditText which creates a DatePicker when is pressed. So I write the following code:
mEditInit = (EditText) findViewById(R.id.date_init);
mEditInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATEINIT_DIALOG);
}
});
But when I press the EditText the action is the typical: a cursor waiting for typing text instead show the Dialog I want.
The keyboard seems to pop up when the EditText gains focus. To prevent this, set focusable to false:
<EditText
...
android:focusable="false"
... />
This behavior can vary on different manufacturers' Android OS flavors, but on the
devices I've tested I have found this to to be sufficient. If the keyboard still pops up, using hints instead of text seems to help as well:
myEditText.setText("My text"); // instead of this...
myEditText.setHint("My text"); // try this
Once you've done this, your on click listener should work as desired:
myEditText.setOnClickListener(new OnClickListener() {...});
Normally, you want maximum compatibility with EditText's normal behaviour.
So you should not use android:focusable="false" as, yes, the view will just not be focusable anymore which looks bad. The background drawable will not show its "pressed" state anymore, for example.
What you should do instead is the following:
myEditText.setInputType(InputType.TYPE_NULL);
myEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// showMyDialog();
}
});
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// showMyDialog();
}
}
});
By setting the input type to TYPE_NULL, you prevent the software keyboard from popping up.
By setting the OnClickListener and OnFocusChangeListener, you make sure that your dialog will always open when the user clicks into the EditText field, both when it gains focus (first click) and on subsequent clicks.
Just setting android:inputType="none" or setInputType(InputType.TYPE_NULL) is not always enough. For some devices, you should set android:editable="false" in XML as well, although it is deprecated. If it does not work anymore, it will just be ignored (as all XML attributes that are not supported).
I had this same problem. The code is fine but make sure you change the focusable value of the EditText to false.
<EditText
android:id="#+id/date"
android:focusable="false"/>
I hope this helps anyone who has had a similar problem!
Default working of EditText:
On first click it focuses and on second click it handles onClickListener so you need to disable focus. Then on first click the onClickListener will handle.
To do that you need to add this android:focusableInTouchMode="false" attribute to your EditText. That's it!
Something like this:
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:inputType="text" />
Here is the solution I implemented
mPickDate.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
showDialog(DATE_DIALOG_ID);
return false;
}
});
OR
mPickDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
showDialog(DATE_DIALOG_ID);
}
});
See the differences by yourself.
Problem is since (like RickNotFred said) TextView to display the date & edit via the DatePicker. TextEdit is not used for its primary purpose.
If you want the DatePicker to re-pop up, you need to input delete (1st case) or de focus (2nd case).
Ray
If you use OnClick action on EditText like:
java:
mEditInit = (EditText) findViewById(R.id.date_init);
mEditInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATEINIT_DIALOG);
}
});
or kotlin:
editTextChooseDate.setOnClickListener {
showDialog(DATEINIT_DIALOG)
}
So, it will work perfectly if you put into xml of your EditText the following lines:
android:inputType="none"
android:focusable="false"
android:cursorVisible="false"
For example:
<EditText
android:id="#+id/date_init"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:hint="Select Date"
android:inputType="none"
android:focusable="false"
android:cursorVisible="false"/>
or for MaterialDesign
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/layoutEditTextChooseDate"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/date_init"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:hint="Select Date"
android:inputType="none"
android:focusable="false"
android:cursorVisible="false"/>
</com.google.android.material.textfield.TextInputLayout>
See https://gist.github.com/Reacoder/0b316726564f85523251:
editText.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
// onClick(editText)
}
}
editText.setOnTouchListener { _, motionEvent ->
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
// onClick(editText)
}
false
}
=== Old answer ===
Nice topic. Well, I have done so.
In XML file:
<EditText
...
android:editable="false"
android:inputType="none" />
In Java-code:
txtDay.setOnClickListener(onOnClickEvent);
txtDay.setOnFocusChangeListener(onFocusChangeEvent);
private View.OnClickListener onOnClickEvent = new View.OnClickListener() {
#Override
public void onClick(View view) {
dpDialog.show();
}
};
private View.OnFocusChangeListener onFocusChangeEvent = new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
dpDialog.show();
}
};
IMHO I disagree with RickNotFred's statement:
Popping a dialog when an EditText gets
focus seems like a non-standard
interface.
Displaying a dialog to edit the date when the use presses the an EditText is very similar to the default, which is to display a keyboard or a numeric key pad. The fact that the date is displayed with the EditText signals to the user that the date may be changed. Displaying the date as a non-editable TextView signals to the user that the date may not be changed.
The following works perfectly for me.
First set your date picker widget's input to 'none' to prevent the soft keyboard from popping up:
<EditText android:inputType="none" ... ></EditText>
Then add these event listeners to show the dialog containing the date picker:
// Date picker
EditText dateEdit = (EditText) findViewById(R.id.date);
dateOfBirthEdit.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
showDialog(DIALOG_DATE_PICKER);
}
return false;
}
});
dateEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showDialog(DIALOG_DATE_PICKER);
} else {
dismissDialog(DIALOG_DATE_PICKER);
}
}
});
One last thing. To make sure typed days, months, or years are correctly copied from the date picker, call datePicker.clearFocus() before retrieving the values, for instance via getMonth().
This Works For me:
mEditInit = (EditText) findViewById(R.id.date_init);
mEditInit.setKeyListener(null);
mEditInit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
{
mEditInit.callOnClick();
}
}
});
mEditInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATEINIT_DIALOG);
}
});
Here is what worked for me
Set editable to false
<EditText android:id="#+id/dob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Date of Birth"
android:inputType="none"
android:editable="false"
/>
Then add an event listener for OnFocusChange
private View.OnFocusChangeListener onFocusChangeDOB= new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){
showDialog(DATE_DIALOG_ID);
}
}
};
As Dillon Kearns suggested, setting focusable to false works fine.
But if your goal is to cancel the keyboard when EditText is clicked, you might want to use:
mEditText.setInputType(0);
Why did not anyone mention setOnTouchListener? Using setOnTouchListener is easy and all right, and just return true if the listener has consumed the event, false otherwise.
The problem with solutions using OnFocusChangeListener is that they interpret any focus gain as a click. This is not 100% correct: your EditText might gain focus from something else than a click.
If you strictly care about click and want to detect click consistently (regardless of focus), you can use a GestureDetector:
editText.setOnConsistentClickListener { /* do something */ }
fun EditText.setOnConsistentClickListener(doOnClick: (View) -> Unit) {
val gestureDetector = GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(event: MotionEvent?): Boolean {
doOnClick(this#setOnConsistentClickListener)
return false
}
})
this.setOnTouchListener { _, motionEvent -> gestureDetector.onTouchEvent(motionEvent) }
}
For kotlin, you could use this
editText!!.showSoftInputOnFocus = false

how to block virtual keyboard while clicking on edittext in android?

How to block virtual keyboard while clicking on edittext in android
Here is a website that will give you what you need.
As a summary, it provides links to InputMethodManager and View from Android Developers. It will reference to the getWindowToken inside of View and hideSoftInputFromWindow() for InputMethodManager.
A better answer is given in the link, hope this helps.
EDIT
From the link posted above, here is an example to consume the onTouch event:
editText.setOnTouchListener(otl);
private OnTouchListener otl = new OnTouchListener() {
public boolean onTouch (View v, MotionEvent event) {
return true; // the listener has consumed the event
}
};
Here is another example from the same website. This claims to work but seems like a bad idea since your EditBox is NULL it will be no longer an editor:
myEditor.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
int inType = myEditor.getInputType(); // backup the input type
myEditor.setInputType(InputType.TYPE_NULL); // disable soft input
myEditor.onTouchEvent(event); // call native handler
myEditor.setInputType(inType); // restore input type
return true; // consume touch event
}
});
Hope this points you in the right direction!
A simpler way, is to set focusable property of EditText to false.
In your xml layout:
<EditText
...
android:focusable="false" />
Another simpler way is adding android:focusableInTouchMode="false" line to your EditText's xml. Hope this helps.
For cursor positioning you can use Selection.setSelection(...), i just tried this and it worked:
final EditText editText = (EditText) findViewById(R.id.edittext);
editText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//change the text here
Selection.setSelection(editText.getText(), editText.length());
return true;
}
});
The best way to do this is by setting the flag textIsSelectable in EditText to true. This will hide the SoftKeyboard permanently for the EditText but also will provide the added bonus of retaining the cursor and you'll be able to select/copy/cut/paste.
You can set it in your xml layout like this:
<EditText
android:textIsSelectable="true"
...
/>
Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);
For anyone using API 10 and below, hack is provided here : https://stackoverflow.com/a/20173020/7550472

Categories

Resources