【发布时间】:2011-03-06 11:56:21
【问题描述】:
我希望使用 ScrollView 中的 TableLayout 来创建一个动态表,随着时间的推移添加行作为用户交互的结果。这很好用,但是当我想使用fullScroll() 滚动到表格末尾时,它总是会忽略最后一行;也就是说,它会滚动以使最后一个之前的那个可见。手动滚动时可以看到最后一行,滚动条也是正确的。
我当然愿意接受有关如何从中做出更好布局的建议;但我特别想了解为什么fullScroll() 会这样。我应该给它一个不同的参数,还是完全使用其他东西?还是因为新添加的行尚不可见而这样做? (如果是这样,我该如何解决?)或者我错过了其他一些明显的事情?
下面的代码复制了这个问题:
TestActivity.java:
package com.example.android.tests;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.AddRow)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random rnd = new Random();
TableRow nr = new TableRow(v.getContext());
for (int c=0; c<3; c++) {
TextView nv = new TextView(v.getContext());
nv.setText(Integer.toString(rnd.nextInt(20)-10));
nr.addView(nv);
}
((TableLayout) findViewById(R.id.Table)).addView(nr);
// Scrolls to line before last - why?
((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);
}
});
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Add Row"
android:id="@+id/AddRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
<ScrollView
android:id="@+id/TableScroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/AddRow"
android:layout_alignParentTop="true" >
<TableLayout
android:id="@+id/Table"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2" />
</ScrollView>
</RelativeLayout>
编辑:供参考,我实现Romain Guy的解决方案如下:
在TestActivity.java中,替换:
// Scrolls to line before last - why?
((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);
与:
// Enqueue the scrolling to happen after the new row has been layout
((ScrollView) findViewById(R.id.TableScroller)).post(new Runnable() {
public void run() {
((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);
}
});
效果很好。
【问题讨论】:
标签: android scrollview tablelayout