1

I cannot for the life of me get my app to programmatically scroll to a position in a wearablerecyclerview. I've tried the following:

  1. Watching for onGlobalLayout and scrolling
  2. Adding a button and scrolling when the button was clicked (just in case there was something going on where the list wasn't fully loaded or was redrawing)
  3. Last ditch effort using Greenrobot eventbus to make sure it happened on the main UI thread, still no scrolling

Here's my layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.wear.widget.BoxInsetLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    app:layout_box="left|bottom|right">
    <Button
        android:id="@+id/gotolast_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Go to last"/>
    <android.support.wear.widget.WearableRecyclerView xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/listview"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        tools:listitem="@layout/item_string" />

</LinearLayout>

here's my code:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // TRYING TO DO IT WITH A MANUAL BUTTON CLICK
    gotolast_button.setOnClickListener {  
        val lastValue = PreferenceManager.getDefaultSharedPreferences(context).getInt(WearMainActivity.PREF_LAST_VALUE, 0)
        (listview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(lastValue,0)
    }

    // TRYING TO DO IT WITH GLOBALLAYOUTLISTENER
    listview.adapter = StringListAdapter(getList()) 
    listview.viewTreeObserver.addOnGlobalLayoutListener ( object:ViewTreeObserver.OnGlobalLayoutListener{
        override fun onGlobalLayout() {
            if (listview.childCount > 0) {
                // scroll to the last selected grade
                val lastValue = PreferenceManager.getDefaultSharedPreferences(context).getInt(WearMainActivity.PREF_LAST_VALUE, 0)
                (listview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(lastValue,0)
                listview.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}

Nothing worked. Any help would be much appreciated!!

chanban
  • 480
  • 1
  • 4
  • 19

1 Answers1

1

You could try to execute scrollToPositionWithOffset within a runnable inside a handler like this

Handler().postDelayed({
   (listview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(lastValue,0)
}, 200).
limpmike
  • 23
  • 1
  • 6