ScrollView是一種特殊的FrameLayout,使用ScrollView可以使使用者能夠滾動一個包含views的列表,這樣做的話,就可以利用比物理顯示地區更大的空間。有一點需要注意一下,那就是ScrollView只能包含一個子視圖view或ViewGroup(這個ViewGroup通常是LinearLayout)。
不要混合使用ListView和ScrollView。ListView被設計用來顯示一些相關的資訊,同時,ListView也已經被最佳化了去顯示大量的列表lists。
下面的main.xml顯示了一個包含LinearLayout的ScrollView,在LinearLayuout中又包含了一些Button和EditText視圖:
[html] view plaincopy<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:id="@+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button3" />
<EditText
android:id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="600dp" />
<Button
android:id="@+id/button4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button4" />
<Button
android:id="@+id/button5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button5" />
</LinearLayout>
</ScrollView>
以上代碼在模擬器上的:
因為EditText自動獲得了焦點,它充滿了整個activity(因為它的高度被設定成了600dp)。如果想阻止這個EditText獲得焦點,那麼只需在<LinearLayout>元素中添加以下兩個屬性:
[html] view plaincopy<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
>
現在,就可以看到那些button按鈕視圖了,同時也可以滾動這些視圖列表。就像下面展示的那樣:
但是有的時候可能想要這個EditText自動擷取焦點,但是又不想軟鍵盤自動地顯示出來。想要阻止軟鍵盤的出現,可以在AndroidManifext.xml中的<activity>節點中,添加如下的屬性:
[html] view plaincopy<activity
android:name=".LayoutActivity"
android:label="@string/app_name"
<!-- 注意這行代碼-->
android:windowSoftInputMode="stateHidden"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
摘自 manoel的專欄