Set focusable and focusableInTouchMode property to false from Kotlin code

From View source code, setFocusable() is method overloading with 2 signatures:

/**
 * Set whether this view can receive the focus.
 * <p>
 * Setting this to false will also ensure that this view is not focusable
 * in touch mode.
 *
 * @param focusable If true, this view can receive the focus.
 *
 * @see #setFocusableInTouchMode(boolean)
 * @see #setFocusable(int)
 * @attr ref android.R.styleable#View_focusable
 */
public void setFocusable(boolean focusable) {
    setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
}

/**
 * Sets whether this view can receive focus.
 * <p>
 * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
 * automatically based on the view's interactivity. This is the default.
 * <p>
 * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
 * in touch mode.
 *
 * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
 *                  or {@link #FOCUSABLE_AUTO}.
 * @see #setFocusableInTouchMode(boolean)
 * @attr ref android.R.styleable#View_focusable
 */
public void setFocusable(@Focusable int focusable) {
    if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
        setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
    }
    setFlags(focusable, FOCUSABLE_MASK);
}

From Kotlin to call:

setFocusable(boolean focusable): using isFocusable property

setFocusable(@Focusable int focusable): using focusable property

Root cause: You call focusable and pass a boolean as param, that why the compiler gave the error.

Solution: Combine two method overloading together

if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
    stb_help_btn.isFocusable = false
} else {
    stb_help_btn.focusable = View.NOT_FOCUSABLE
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top