Android edittext set focus

Установка фокуса на EditText

В xml у editText есть эти 2 атрибута:

Пытался установить фокус с помощью такого кода:

UPD:
Подробнее.
В Navigation Drawer-е нажимаю кнопку, он закрывается, дальше во фрагменте (вкладки) пытаюсь установить фокус.

Никакие задержки не помогли.
editText.requestFocus() возвращает true .

Добавил к View , на который хочу установить фокус, OnFocusChangeListener . Сначала hasFocus равен true , а потом false .

Thread Dupm при hasFocus==false :

3 ответа 3

Судя по всему вы не понимаете разницу между получением фокуса и показом клавиатуры. Они вообще то отличаются. Получение фокуса не означает показа клавиатуры, и обратно также верно — показ клавиатуры не означает наличия фокуса. Теоретически ведь устройство может иметь хардверную клавиатуру или иное устройство ввода, так что не надо путать фокус и показ виртуальной клавиатуры друг с другом.

Возвращаясь к сути вопроса, чтобы совместить получение фокуса и показ виртуальной клавиатуры используйте такой код:

По хорошему, этот способ надо совмещать с проверкой на наличие хардверной клавиатуры:

Проблема решилась добавлением этой строки перед requestFocus :

Строку android:focusableInTouchMode=»true» в файле разметки android почему-то игнорирует.

Попробуй вынести эту логику в метод статический и вынеси его в какой-нибудь класс Utils.

Что-то на подобие такого и добавь задержку как в моем примере, это должно сработать (Давно боролся с этой проблемой — не помню в чем там суть, но точно какая то неприятная ерунда).

Источник

How can I set the focus (and display the keyboard) on my EditText programmatically

I have a layout which contains some views like this:

How can I set the focus (display the keyboard) on my EditText programmatically?

I’ve tried this and it works only when I launch my Activity normally, but when I launch it in a TabHost , it doesn’t work.

15 Answers 15

This worked for me, Thanks to ungalcrys

showSoftInput was not working for me at all.

I figured I needed to set the input mode : android:windowSoftInputMode=»stateVisible» (here in the Activity component in the manifest)

Here is how a kotlin extension for showing and hiding the soft keyboard can be made:

Then you can just do this:

I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause :

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:

Here is KeyboardHelper Class for hiding and showing keyboard

I tried a lot ways and it’s not working tho, not sure is it because i’m using shared transition from fragment to activity containing the edit text.

Читайте также:  Клавиатура для андроида swiftkey

Btw my edittext is also wrapped in LinearLayout.

I added a slight delay to request focus and below code worked for me: (Kotlin)

Put this into onResume() method.

First way:

Second way:

I tried the top answer by David Merriman and it also didn’t work in my case. But I found the suggestion to run this code delayed here and it works like a charm.

I finally figured out a solution and create a Kotlin class for it

I couldn’t get any of these answers to work on their own. The solution for me was to combine them:

I’m not sure why that was required for me — according to the docs it seems that either method should have worked on their own.

Источник

EditText request focus not working

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

13 Answers 13

ensure that the edittext is focusable in touch mode. You can do it two way.

Personally I don’t trust the XML definition of this param. I always request focus by these two lines of code:

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:

I hope it was helpful

The following works for me and should help:

In your manifest.xml write:

And call m_SearchEditText.requestfocus() in oncreate() .
OR,
Try:

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:

Minimalist Kotlin extension version because we should pretend these sorts of obtuse calls into system services are not necessary:

Following saleh sereshki’s answer and pauminku’s comment, I’m using:

which in Kotlin is the equivalent to:

U need two xml attributes also to achieve this:

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.

Читайте также:  Trojan android os multiverse

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

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 :

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 .

and at the end you can use this kotlin extention to do all of this for you :

Источник

Android: Force EditText to remove focus? [duplicate]

I would like to be able to remove the focus from the EditText. For example if the Keyboard appears, and the user hides it with the back button, I would like the focus and the cursor to disappear. How can it be done?

19 Answers 19

You can make cursor and focus disappear by

But detect when the key board hide is a hard work.

You can add this to onCreate and it will hide the keyboard every time the Activity starts.

You can also programmatically change the focus to another item.

Add LinearLayout before EditText in your XML.

Or you can do this same thing by adding these lines to view before your ‘EditText’.

Remove focus but remain focusable:

EditText will lose focus, but can gain it again on a new touch event.

It’s working for me

Edit In the link they suggest to use LinearLayout, but simple View will work

Then if this «thief» is placed at the top of the layout (to be first focusable item) calls to clearFocus() will work.

Add these two properties to your parent layout (ex: Linear Layout, Relative Layout)

It will do the trick 🙂

You can also include android:windowSoftInputMode=»stateAlwaysHidden» in your manifest action section.

This is equivalent to :

FYI, you can also hide the keyboard with codes:

To hide the keyboard when activity starts.. write the following code in onCreate()..

To clear focus and remove cursor from edittext.

try to use this one on your view it worked for me:

Add to your parent layout where did you put your EditText this android:focusableInTouchMode=»true»

you have to remove

if you don’t use it and still the same problem

user LinearLayout as a parent and set

Hope it’s help you.

This is my very first answer on SO, so don’t be too harsh on me if there are mistakes. 😀

There are few answers floating around the SO, but I feel the urge to post my complete solution cause this drove me nuts. I’ve grabbed bits and pieces from all around so forgive me if I don’t give respective credits to everyone. 🙂

Читайте также:  Читай город для андроид

(I’ll simplify my result cause my view has too many elements and I don’t wanna spam with that and will try to make it as generic as possible. )

For your layout you need a parent your EditText and parent view defined something like this:

So, I needed a few things here. I needed to have a Placeholder for my EditText — which is that —

made it happen for EditText not to be focused on entering the Activity and later on in the Activity itself when setting it this setting helps so you can set onTouchListener on it to steal the focus away from EditText.

Now, in the Activity:

Few of the answers for bits I found on this question page, and the part with the Activity solution I found on this blog. The rest I missed which I had to figure out myself was clearing focus on the EditText which I added to both inside the setOnEditorActionListener and onTouchLister for the parent view.

Hope this helps someone and saves their time. 🙂

Источник

How to set focus on a TextView when an Activity starts?

There are an EditText and a TextView in my Activity. I want to set focus on the TextView when the Activity starts. I used the following code:

But the code doesn’t work. The EditText always receives focus when the activity starts.

Can anyone help?

7 Answers 7

This is expected when you start the Activity using the touch screen. When in «touch mode,» only a couple of Views (EditText and ListView) can receive the focus. If you start your application using the trackball you will see the focus on the TextView. What you are seeing is the correct and expected result.

I came across with your question now. Maybe after 2 years you have found a solution. But I write it here for the others that will come across with this in the future. The only thing you have to do is to go to the AndroidManifest.xml , find the Activity in which you want this behaviour and add this android:windowSoftInputMode=»stateHidden» . So, at the start of your Activity no keyboard will be shown, until you touch the EditText object.

If anyone is still wondering, you can use the following in your layout xml to make a textview focusable in touch mode:

In order to request focus to TextView you need to set focusable=»true» and focusableInTouchMode=»true» as follows:

Add the TextView Property in layout

It’s work for me.

This takes focus off of the EditText and puts it on the TextView.

You can set focus to any widget or a TextView from the xml of the activity. Just add requestFocus before the TextView end.

Источник

Оцените статью