可滚动的 LinearLayout 高度限制

Scrollable LinearLayout height limitation

我正在以编程方式在 LinearLayout 中添加 TextView,我想确保如果 TextView 超过特定数量,用户将能够向下滚动。我将 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。你可以找到一个简单的例子 here.

这是处理大列表的最佳方法。

在您的 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>

试试这个。我希望工作...

<?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>