代码之家  ›  专栏  ›  技术社区  ›  Nico Dioso

如何在单击时将布局置于滚动视图的中心?

  •  0
  • Nico Dioso  · 技术社区  · 8 年前

    我这里有这样的布局:

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollView"
        >
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:id="@+id/instructions">
    
                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="Sample text 1"/>            
    
                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="Sample text 2"/>            
    
                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="Sample text 3"/>      
    
    
        </LinearLayout>
    
    </ScrollView>
    

    (为了简单起见,我刚把它改成了textView3,但如果说还有更多,scrollView是可滚动的),那么在这个scrollView外有一个按钮。每次单击按钮时,scrollView都会滚动视图,并将视图居中放置到下一个textView。我怎样才能做到这一点?

    我尝试获取视图的高度,然后将其添加到scrollView上。scrollTo(y),但检索高度给了我很多问题,我使用了ViewTreeObserver进程,但无法检索

    .addOnGlobalLayoutListener(新ViewTreeObserver。。。

    并将其放置在变量上。但我用这种方法失败了。我做错了什么?还是有更简单的方法?

    1 回复  |  直到 8 年前
        1
  •  0
  •   insa_c    8 年前

    您可以考虑使用 RecyclerView 并向列表中添加新项目,然后调用 scrollToPosition(position) 功能可滚动至最新版本。 别忘了添加 paddingBottom 回收视图 可以将最后一个视图滚动到中间。(使用 screenHeight / 2 对于 填充底部 )