在实际开发过程中,会需要动态添加控件到ScrollView,就需要在Java代码中,找到ScrollView的孩子(ViewGroup),进行添加即可。

 

Layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- ScrollView里面只能包含一个孩子,才是正确的👌 -->
        <LinearLayout
            android:id="@+id/ll_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

 

Java动态添加的代码:

package liudeli.ui.all;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ScrollViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrollview);

        // 找到ScrollView的孩子(ViewGroup),进行添加即可
        LinearLayout llContent = findViewById(R.id.ll_content);
        for (int i=0; i<80; i++) {
            TextView textView = new TextView(this);
            textView.setText("找到ScrollView的孩子(ViewGroup)" + i);
            textView.setTextSize(20);
            textView.setTextColor(Color.BLUE);
            textView.setGravity(Gravity.CENTER);
            llContent.addView(textView);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

 

结果: