我有一个包含 LinearLayout 的 HorizontalScrollView。在屏幕上,我有一个按钮,它将在运行时将新视图添加到 LinearLayout,并且我希望滚动视图在添加新视图时滚动到列表的末尾。
我几乎让它工作了——除了它总是在最后一个视图之外滚动一个视图。似乎它在没有首先计算包含新视图的情况下滚动。
在我的应用程序中,我使用的是自定义 View 对象,但我制作了一个使用 ImageView 并具有相同症状的小型测试应用程序。我在 Layout 和 ScrollView 上尝试了各种类似 requestLayout() 的方法,我尝试了 scrollTo(Integer.MAX_VALUE) 并且它滚动到了下界:) 我是在违反 UI 线程问题还是什么?
- 瑞克
======
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.addButton);
b.setOnClickListener(new AddListener());
add();
}
private void add() {
LinearLayout l = (LinearLayout) findViewById(R.id.list);
HorizontalScrollView s =
(HorizontalScrollView) findViewById(R.id.scroller);
ImageView i = new ImageView(getApplicationContext());
i.setImageResource(android.R.drawable.btn_star_big_on);
l.addView(i);
s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
}
private class AddListener implements View.OnClickListener {
@Override
public void onClick(View v) {
add();
}
}
}
布局 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<HorizontalScrollView
android:id="@+id/scroller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbarSize="50px">
<LinearLayout
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4px"/>
</HorizontalScrollView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="80px"
android:paddingRight="80px"
android:paddingTop="40px"
android:paddingBottom="40px"
android:text="Add"/>
</LinearLayout>
</LinearLayout>