How to add Rotary Input into ScrollView in Android Wear

1.1k Views Asked by At

I am working on an android wear app, I already added rotary input to recyclerview using rcView.requestFocus(),but it doesn't work with NestedScrollview so I want to know how to add the rotary input listener to NestedScrollview.

Here is what I have done so far

   binding.mainScroll.setOnGenericMotionListener { v, ev ->
            if (ev.action == MotionEvent.ACTION_SCROLL &&
                ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)
            ) {

                val delta = -ev.getAxisValue(MotionEventCompat.AXIS_SCROLL) *
                        ViewConfigurationCompat.getScaledVerticalScrollFactor(
                            ViewConfiguration.get(applicationContext), applicationContext
                        )
                
                v.scrollBy(0, delta.roundToInt())
                true
            } else {
                false
            }
        }
2

There are 2 best solutions below

0
On

On your activity_layout add requestFocus inside the ScrollView. You need your API to be 28 or higher. Example:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <requestFocus
        android:focusable="true"
        android:focusableInTouchMode="true"/>
</ScrollView> 
0
On

You need to make the target scrollable view focusable, AND focusable in touch mode, AND request the focus:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <requestFocus/>
</ScrollView>