Android ApiDemos示范解析(154):Views->Layouts->ScrollView->2. Long

Android ApiDemos示例解析(154):Views->Layouts->ScrollView->2. Long

本例使用ScrollView显示一个长列表,其定义的scroll_view_2.xml

<ScrollView xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:scrollbars=”none”>

<LinearLayout
android:id=”@+id/layout”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”@string/scroll_view_2_text_1″/>

<Button
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”@string/scroll_view_2_button_1″/>

</LinearLayout>
</ScrollView>


ScrollView 只定义了一个TextView 和 Button在LinearLayout中,而在ScrollView2.java 使用代码为LinearLayout 动态添加了63个TextView 和Button:

LinearLayout layout
 = (LinearLayout) findViewById(R.id.layout);
for (int i = 2; i < 64; i++) {
 TextView textView = new TextView(this);
 textView.setText("Text View " + i);
 LinearLayout.LayoutParams p
 = new LinearLayout.LayoutParams(
 LinearLayout.LayoutParams.MATCH_PARENT,
 LinearLayout.LayoutParams.WRAP_CONTENT
 );
 layout.addView(textView, p);

 Button buttonView = new Button(this);
 buttonView.setText("Button " + i);
 layout.addView(buttonView, p);
}


 

从而构成一个长列表,一屏肯定显示不下,此时就可以滚动屏幕来显示:

Android ApiDemos示范解析(154):Views->Layouts->ScrollView->2. Long