Ericsen Cioffi
Ericsen Cioffi

Reputation: 61

Android - How can I prevent view focus changes?

I´d like to implement something like a "beforeLosingFocus" event to my controls (EditText) and I want to be able to prevent the focus changes so my control must have the focus until the user type allowed values.

I tried to use onFocusChange event but this event is fired after the focus changes. This event is fired two times (because one control lost the focus while another control get it).

Is possible to prevent that another control get the focus in a generic way? (because the focus can change by a tap in another control or a "Next" key click)

Upvotes: 6

Views: 7356

Answers (3)

StepanM
StepanM

Reputation: 4402

editText.setOnEditorActionListener {
    ...
        if (actionId == EditorInfo.IME_ACTION_NEXT) {
            return true // if you want to ignore IME_ACTION_NEXT
            return false // if you want to lose focus and go further
        }
    ...
    }

Upvotes: 2

Sam
Sam

Reputation: 86948

Override your EditText's OnFocusChangeListener with for "in activity" changes and override the navigation buttons' OnClicks to perform an integrity test.

EDIT (It helps if I proof read, sorry)

You mentioned that know how to override the onFocusChange(View view, boolean state) in your EditText to force the user to enter text by checking if(state == false). But you also discovered, when the user clicks a navigation button (like Next) the onFocusChange is never called before starting a new activity.

So keep the onFocusChange if you have more than one EditText (for example username and password) and add a check inside your Next button's onClickListener to verify that the user has entered text in your EditText before you start a new activity.

Upvotes: 0

Akhil
Akhil

Reputation: 14038

Two ways you can do this: 1) keep all the other views's setFocusable property to false by default. Then enable them as per your logic, one by one.

2) When onFocusChangedListener is called, set the focus back to the view you want using v.requestFocus() .

Upvotes: 1

Related Questions