Currently, when clicking into TextField or similar where manual input is requred the android virual keyboard pops up automaticaly, is there a way to prevent it and set it only when i manualy double click into the TextField?
Ref: How to stop EditText from gaining focus at Activity startup in Android
<LinearLayout
android:focusable="true" //insert this line in your parent layout
android:focusableInTouchMode="true"//insert this line in your parent layout
android:layout_width="0px"
android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="#+id/autotext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:nextFocusUp="#id/autotext"
android:nextFocusLeft="#id/autotext"/>
What this does is it makes the parent layout get the focus by deafult. Hence the focus will be present on the text view only if you press it twice
in Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_setting)
//add for keyboard don't open automatically
this.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
// and edit text enable false
edittext.isEnabled = false
editText.setOnClickListener(new View.OnClickListener() {
int count = 0;
Handler handler = new Handler();
Runnable runnable = () -> count = 0;
#Override
public void onClick(View v) {
if (!handler.hasCallbacks(runnable))
handler.postDelayed(runnable, 500);
if(count==2){
edittext.isEnabled = true
showKeyboard(editText, thiscontext!!)
//
}
}
});
//..............
fun showKeyboard(editText: EditText, context: Context) {
editText.post {
editText.requestFocus()
val imm = editText.context
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}
}
Related
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)
}
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.
I'm having a Floating Action Button listener with AlertDiaolog inside. And I want to use my buttons from XML. And if I want to write an onClickListener() for them.
So in Java I have to initialize it like:
butAdd = (Button)dialog.findViewById(R.id.btn_add)
butAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Some code
}
But when I trying to use:
var butAdd = dialog?.findViewById(R.id.btn_add) as Button;
in Kotlin it's incorrect
So any suggestions how to fix it? What'is wrong with listeners?
Here is my code of Floating Action Button:
fab?.setOnClickListener {
diaolg = AlertDialog.Builder(this#Cards)
val linearlayout = getLayoutInflater().inflate(R.layout.add_password, null)
diaolg?.setView(linearlayout)
?.setTitle("Add a new password")
?.setCancelable(true)
var login = findViewById(R.id.login) as EditText
var password = findViewById(R.id.password) as EditText
var title = findViewById(R.id.title) as EditText
var butAdd = diaolg?.findViewById(R.id.btn_add) as Button
var butCancel = diaolg?.findViewById(R.id.btn_cancel) as Button
butAdd.setOnClickListener(View.OnClickListener {
fun onClick(v:View){
}
})
butCancel.setOnClickListener(View.OnClickListener {
fun onClick(v:View){
}
})
diaolg?.create()
diaolg?.show()
}
please find id by using
var butAdd = linearlayout.findViewById<Button>(R.id.btn_add) as Button;
Whatever class you're in has no findViewById method.
You have to findViewById on the inflated layout, so:
var login = linearLayout.findViewById(R.id.login) as EditText
Also, I dont think you need to have the ? on the dialog, it cannot be null.
Also, I would make your views vals instead of vars.
import this line in your Activity
<Button
android:id="#+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="submit" />
import this line in your Activity
// Using R.layout.activity_main from the main source set
//activity_main is your layout file name
import kotlinx.android.synthetic.main.activity_main.*
btn_submit.setOnClickListener {
Toast.makeText(this, "hello", Toast.LENGTH_LONG).show();
}
Its work for me.
I am working on Android Smart TV application:
In a view there is a custom keyboard and an EditText.
When application launches focus goes to the keyboard.
Desired:
When the user types with keyboard (clicking with a remote) the cursor should also blink inside the editText.
How can I show this effect inside the EditText?
This happens if you set a background for the field. If you want to solve this, set the cursorDrawable to #null.
You should add textCursorDrawable with cursorVisible.
Reference to a drawable that will be drawn under the insertion cursor.
android:cursorVisible="true"
android:textCursorDrawable="#null"
You could try something like this:
editText.setText(text);
editText.setPressed(true);
editText.setSelection(editText.getText().length()); // moves the cursor to the end of the text
However, there are 2 problems with this approach:
The cursor will not blink. The logic for the blinking is in the Editor class and cannot be overridden. It requires that the EditText is focused, and only 1 View can be focused at once within a Window - in your case that will be one of the keyboard buttons.
/**
* #return True when the TextView isFocused and has a valid zero-length selection (cursor).
*/
private boolean shouldBlink() {
if (!isCursorVisible() || !mTextView.isFocused()) return false;
...
}
The cursor will not always be visible. The blinking of the cursor is based on the System time - it is visible for half a second, and hidden for the next half a second. The cursor will only be visible if the code I suggested above is called at a point in time when the cursor would be visible according to the System time.
This is why the native keyboard/IME works the way it does. It is a separate Window that allows the EditText to maintain focus and have the blinking cursor functionality, while the user is tapping on Views in a different Window (the keyboard/IME).
That being said, there is a workaround for the problems above - make sure to set shouldBlink to false when you no longer need it though, it's a guaranteed memory leak or crash otherwise:
private void blink() {
if (shouldBlink) {
editText.setText(editText.getText());
editText.setPressed(true);
editText.setSelection(editText.getText().length());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (shouldBlink) {
blink();
}
}
}, 500);
}
}
You can do this..I hope/think that u have a layout for the buttons u have created, by this u can set a Focus Listener for that layout and inside the onFocusChange method you can check if(layout.hasFocus()) and do this...
For example if your editText is named as et, u can set this to it:
et.setActivated(true);
et.setPressed(true);
I have a small example code for you having two edit text
et2.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(et2.hasFocus()){
//et1.setCursorVisible(true);
et1.setActivated(true);
et1.setPressed(true);
}
}
});
In your layout xml file add the following line in your edit text:
<requestFocus/>
This will place the cursor in your editText widget.
Hope it helps.
simply add
editText.requestFocus();
There is a couple of ways doing it:
1) XML
android:cursorVisible="true"
2) Java
mEditText.setOnClickListener(editTextClickListener);
OnClickListener editTextClickListener = new OnClickListener() {
public void onClick(View v) {
if (v.getId() == mEditText.getId()) {
mEditText.setCursorVisible(true);
}
}
};
or
if (mEditText.hasFocus()){
mEditText.setCursorVisible(true);
}
I know this is necro, but this was much better than the solutions above. Just extend EditText and add:
#Override
public boolean isCursorVisible() {
return true;
}
#Override
public boolean isFocused() {
return true;
}
And in your XML:
<com.foo.MyEditText
...
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:cursorVisible="true"/>
Now the EditText thinks it is focused and the cursor is visible, but it actually can't be focused.
private void setFocusCursor(){
mBinding.replyConversationsFooter.footerEditText.setFocusable(true);
`mBinding.replyConversationsFooter.footerEditText.setFocusableInTouchMode(true);`
`mBinding.replyConversationsFooter.footerEditText.requestFocus();`
}
Just call this function in oncreateView() and there you go.
We can only set one and only focus on a window.So doing this will help you solve your problem.
You can use the following code in your Activity:
//Get the EditText using
EditText et = (EditText)findViewById(R.id.editText);
//Set setCursorVisible to true
et.setCursorVisible(true);
You can explicitly put caret to last position in text:
int pos = editText.getText().length();
editText.setSelection(pos);
This will always focus on first character on edittext.
android:focusable="true"
Tested on API 27, 28 emulator.
Remove a background attribute, add focusable:
<EditText
...
android:focusable="true"
android:focusableInTouchMode="true"
/>
In code write: edit.requestFocus(); Though an underline will be visible.
In order to remove an underline, see https://stackoverflow.com/a/52052087/2914140:
edit.getBackground().mutate().setColorFilter(ContextCompat.getColor(getContext(), R.color.white), PorterDuff.Mode.SRC_ATOP);
To change a color of the cursor see https://stackoverflow.com/a/49462015/2914140:
add android:textCursorDrawable="#drawable/shape_cursor", while shape_cursor is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size
android:width="1dp"
android:height="25dp"
/>
<solid android:color="#color/gray" />
</shape>
It works on API 27, 28 emulator, but on a real device (API 21) cursor disappears. I tried many variants from here and there, but nothing helped.
Then I noticed that when EditText contains at least one symbol, it shows cursor. I added a TextWatcher to add a space when nothing entered.
private lateinit var someText: String
...
edit.requestFocus()
edit.setText(" ")
edit.addTextChangedListener(YourTextWatcher())
private inner class YourTextWatcher : TextWatcher {
override fun afterTextChanged(s: Editable?) {
someText = s.toString().trim()
if (someText.isEmpty()) {
// To not fall into infinite loop.
if (s?.length != 1) {
edit.setText(" ")
}
} else {
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
Also you can add paddings in order to tap inside EditText, if it is small.
I did like this:
var msgEditText = dialog.findViewById(R.id.msg1textView) as EditText
msgEditText.isActivated = true
msgEditText.isPressed = true
msgEditText.requestFocus()
msgEditText.setSelection(view.getText().length)
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)
}
}