ScrollView上放置button

ScrollView下放置button
http://dev.10086.cn/cmdn/bbs/thread-21816-1-1.html




最近做项目时遇到了这个问题,想要在ScrollView之后显示元素,无论怎么调整Layout的布局,此元素总是无法正确显示——不是跟在ScrollView最下面,就是干脆不显示;着实让人头痛。
依靠万能的Google总是能够得到些许启发。终于让偶找到了类似的做法。
示例代码如下:
view source
print?
01 <LinearLayout android:layout_height="fill_parent"
02 android:layout_width="fill_parent" android:orientation="vertical"
03 xmlns:android="http://schemas.android.com/apk/res/android">
04
05 ...
06
07 <ScrollView android:fillViewport="true"
08 android:layout_height="wrap_content"
09 android:layout_width="fill_parent"
10 android:layout_marginBottom="50dip">
11
12 ...
13
14 </ScrollView>
15
16 <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
17 android:text="I'm below ScrollView"
18 android:layout_marginTop="-50dip" />
19 </LinearLayout>
以上代码实现的效果就是这样的:

看起来,下面的按钮浮于Layout的上面,其实滚动条滚动到按钮的上边缘就结束了。注意上述代码中的ScrollView&Button元素内的参数,分别是layout_marginBottom&layout_marginTop。

不过上述此法并非最佳,为何?也有如此一种情况——紧跟在ScrollView之后的不是静态内容,而是动态的,怎么办?如果是动态的,意味着这部分内容是随时显示的,按照上面的做法,在内容没有显示出来的情况下 ,仍然会出现50dip的占用区域,这对Layout整体效果大打折扣了,看图便知:
这个时候"I’m below ScrollView”按钮已经隐藏了,但是依然留下了那龌龊的一块,有图为证。


以下代码将解决这个问题:
view source
print?
01 <LinearLayout android:layout_height="fill_parent"
02 android:layout_width="fill_parent" android:orientation="vertical"
03 xmlns:android="http://schemas.android.com/apk/res/android">
04
05 ...
06
07 <ScrollView android:fillViewport="true"
08 android:layout_height="wrap_content"
09 android:layout_width="fill_parent"
10 android:layout_weight="1">
11
12 ...
13
14 </ScrollView>
15
16 ...
17
18 </LinearLayout>
注意到了么?去除layout_margin Bottom&layout_marginTop属性,在ScrollView元素中加入android:layout_weight=”1”即可。
演示效果如下:

      「按钮没出现时」
Look!在没有出现那部分内容时,滚动条一直到底,只有出现"I’m below ScrollView”按钮时,滚动条才会往上移动,效果如下:

         「按钮出现」
这个方法是不是很灵光呢?的确如此,至少解决了我的项目问题。但是有个值得开发人员注意的地方,那就是*容器只能是LinearLayout。
上面只讲到了ScrollView之后的元素,还有一个控件会出现滚动条,那就是ListView,这个控件就更加简单了,只有在之后的元素添加上一个属性就行,例如把上面的"I'm below ScrollView”按钮的android:layout_alignParentBottom属性设置为"true”即可。
还有其他很多种情况,或许你还会遇到ListView和ScrollView共存,这些有待你们自己去探索了。
其实,很多Android程序员都被页面的布局所困扰,其实不用太担心和害怕它,掌握几点原则就行了:
(1) 越简单越好
(2) 如果复杂,尽量确保*Layout是LinearLayout
(3) 尽量不要嵌套很多Layout,这会造成性能的大减
(4) 巧妙运行FrameLayout,它能带来很多意想不到的效果
(5) 尽量别用AbsoluteLayout,布局很难调整,兼容性很差