为了可以让内嵌布局管理器之中加入多个显示的组件,而且又保证程序不这么冗余,所以可以通过
Activity程序进行控制,向内嵌布局管理器中添加多个组件。
ScrollView提供一个显示的容器,可以包含多个组件并进行滚动。
在ScrollView中只能包含一种组件。
在main.xml文件中代码如下:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView //注意改标签
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myscroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mylinear"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
在MyScrollViewDemo.java中代码如下:
package com.tarena.scrollview;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class MyScrollViewDemo extends Activity {
private String data[] = {"李叶文","helloliyewen@163.com","广西省北海市银海区",
"诸葛亮","zhugeliang@163.com","南阳",
"司马懿","simayi@163.com","许昌",
"周瑜","zhouyu@163.com","江东"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main); //调用默认的布局管理器
LinearLayout layout = (LinearLayout) super.findViewById(R.id.mylinear); //取得组件
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT); //定义布局参数
for(int x = 0 ; x < this.data.length; x++){ //通过循环方式将以上的信息通过Button组件进行封装
Button but = new Button(this);
but.setText(this.data[x]); //设置文字
layout.addView(but,params); //增加组件
}
}
}