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的专栏