scrollToPositionWithOffset不能与android WearableRecyclerView一起使用

时间:2018-05-25 18:49:51

标签: android kotlin android-wear-2.0

我不能为我的生活让我的应用程序以编程方式滚动到wearablerecyclerview中的位置。我尝试过以下方法:

  1. 观看onGlobalLayout并滚动
  2. 添加按钮并在单击按钮时滚动(以防万一有些内容没有完全加载或正在重新绘制)
  3. 使用Greenrobot eventbus确保它发生在主UI线程上,仍然没有滚动
  4. 的最后努力

    这是我的布局:

    <?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>
    

    这是我的代码:

    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)
                }
            }
        })
    }
    

    没有任何效果。任何帮助将不胜感激!!

1 个答案:

答案 0 :(得分:0)

您可以尝试在像这样的处理程序内的runnable中执行scrollToPositionWithOffset

function() {
    if [something happens]; then return 0; else return 1; fi
}

while [ ... ]
do
   if function; then break; fi
done