由于屏幕的高度有限,面对组件显示多组信息时,我们就可以使用scrollview有效的安排组件,浏览时通过滚屏显示,scrollview是FrameLayout 的子类,所以只是提供一个显示的容器。
使用过程中要注意以下两点 1.scrollview只是提供一个显示的容器,可以包含多个组件进行滚屏;2.scrollview只能包含一种组件,下面通过实例讲解:
1.scrollview的视图定义格式,必须在Scrollview中内嵌一个线性布局,组件的添加通过activity添加
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/mylayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
</LinearLayout>
</ScrollView>
2.通过activity添加组件
public class MainActivity extends Activity {
private String[] data= new String[20];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main); // 调用默认的布局管理器
LinearLayout layout = (LinearLayout) super.findViewById(R.id.mylayout); // 取得组件
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT); // 定义布局参数
for (int x = 0; x < this.data.length; x++) { // 通过循环方式将以上的信息通过Button组件进行封装
data[x]="item"+x;
Button but = new Button(this);
but.setText(this.data[x]); // 设置显示文字
layout.addView(but, param); // 增加组件
}
}
}
效果图如下: