[英]Scroll a TextView in TableLayout into the visible area of screen
如果TextView
不是ScrollView
的直接子級,如何通過滾動ScrollView
將TextView
放入屏幕的可見區域?
我有一個LinearLayout
視圖,該視圖的頂部是TextView
,然后是ScrollView
而在Button
下面:
<LinearLayout
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"/>
<ScrollView
android:id="@+id/s"
android:layout_height="0dip"
android:layout_weight="1" >
<TableLayout
android:id="@+id/t"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/r" >
<TextView
android:id="@+id/a"/>
<TextView
android:id="@+id/b"/>
<TextView
android:id="@+id/c"/>
</TableRow>
</TableLayout>
</ScrollView>
<Button
android:layout_height="wrap_content"/>
</LinearLayout>
這樣就產生了一個完全填充的屏幕,頂部的標簽是標簽,底部的按鈕是按鈕,中間是桌子。 根據此表有多少行,您是否可以滾動它。
該表的內容是由Java代碼生成的,我只添加了一行作為插入其中的示例。
現在,我需要通過垂直滾動確保某個行(不一定是最后一行)可見。 我可以訪問從s
到c
每個元素,但是我根本無法弄清楚使ScrollView s
滾動的代碼。
我嘗試了requestChildRectangleOnScreen
, scrollBy
和scrollTo
,但可能總是帶有錯誤的參數。
現在我不在乎TextView a
是垂直居中還是在底部或頂部邊框,如果它是可見的,那的確很棒。 理想情況下,X滾動應保持為0(即最左側的位置)。
如果這很重要:僅當用戶使用特殊的Intent進入屏幕時才調用此函數,該Intent告訴屏幕滾動到TableRow
x(僅用於顯示最新更改)。
如果您需要更多信息,請詢問。
謝謝!
問題的確是我直接從onCreate
的子調用中調用了該函數。 這意味着尚未完成布局,因此所有滾動都在元素具有高度之前完成,因此滾動了0個像素。
解決方案是使用View.post(Runnable r)
:
ScrollView s = (ScrollView) findViewById(R.id.s);
TextView a = (TextView) findViewById(R.id.a);
s.post(new Runnable() {
public void run() {
int[] location = new int[2];
a.getLocationInWindow(location);
int y = location[1];
s.getLocationInWindow(location);
s.scrollTo(0, y-location[1]); // or some other calculation
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.