我正在以编程方式在线性布局中添加TextViews,我想确保如果TextViews超过一定数量,用户将能够向下滚动。我将LinearLayout包含在ScrollView中,它可以在一定限制下正常工作。在此限制之后,将根本不显示俯视图。
我正在使用以下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linear_layout_with_scrollview);
for (int i = 0; i < 500; i++) {
createView(String.valueOf(i));
}
}
private void createView(String text){
TextView tv = new TextView(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0,15,0,0);
tv.setLayoutParams(lp);
tv.setText(text);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,20);
LinearLayout layout=findViewById(R.id.linear_layout);
layout.addView(tv);
}
对于布局:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_height="wrap_content" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</ScrollView>
这不是我正在使用的实际代码,而是演示问题的简化版本。
我建议使用RecyclerView。你可以在这里找到一个简单的例子。
这是处理大列表的最佳方法。
试试这个。 我希望工作...
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_height="wrap_content" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:layout_height="matchparent" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</ScrollView>
在scrollview
中使用android:fillViewport="true"
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fillViewport="true"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</ScrollView>