1.知识准备:
当内容大于手机高度的时候,就可以使用Scrolliew,这个布局包含view可以被用户滚动,允许内容大于屏幕物理尺寸。他是个帧布局可以放置(只有一个)一个子元素并且包含滚动内容,子元素通常是个线性布局;这个线性布局是个垂直布局items,需要注意的是Scrolliew会和listView形成事件冲突。采用事件分发机制进行解决。
2.基本用法:
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true">
<LinearLayout
android:id="@+id/line"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
private ScrollView scrollView;
private LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollView = (ScrollView) this.findViewById(R.id.scrollView1);
layout = (LinearLayout)this.findViewById(R.id.line);
for(int i=0;i<10;i++ ){
//添加10张图片
ImageView imageView = new ImageView(this);
Drawable drawable = getResources().getDrawable(R.drawable.a);
imageView.setImageDrawable(drawable);
layout.addView(imageView,i);
}
}
3.常用属性方法
一、ScrollView.scrollTo(0,0) 直接置顶,瞬间回到顶部,没有滚动过程,其中Y值可以设置为大于0的值,使Scrollview停在指定位置;
二、ScrollView.fullScroll(View.FOCUS_UP) 类似于手动拖回顶部,有滚动过程;
三、ScrollView.smoothScrollTo(0, 0) 类似于手动拖回顶部,有滚动过程,其中Y值可以设置为大于0的值,使Scrollview停在指定位置。
android:scrollbars
设置滚动条显示。none(隐藏),horizontal(水平),vertical(垂直)
android:scrollbarStyle
设置滚动条的风格和位置。设置值:insideOverlay、insideInset、outsideOverlay、outsideInset
android:scrollbarThumbHorizontal
设置水平滚动条的drawable。
android:soundEffectsEnabled
设置点击或触摸时是否有声音效果
android:fadingEdge
设置拉滚动条时,边框渐变的放向。none(边框颜色不变),horizontal(水平方向颜色变淡),vertical(垂直方向颜色变淡)。参照fadingEdgeLength的效果图 android:fadingEdgeLength 设置边框渐变的长度
android:scrollX
以像素为单位设置水平方向滚动的的偏移值,在GridView中可看的这个效果
android:scrollY
以像素为单位设置垂直方向滚动的的偏移值
android:scrollbarAlwaysDrawHorizontalTrack
设置是否始终显示垂直滚动条
android:scrollbarDefaultDelayBeforeFade
设置N毫秒后开始淡化,以毫秒为单位。
ScrollView滑动监听:
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
//l:当前横向滑动距离
//t:当前纵向滑动距离
//oldl:之前横向滑动距离
//oldt:之前纵向滑动距离
}
}
4.后记
在使用过程中常常会重写子view的布局,从而解决scrollview嵌套其他布局出现的各种奇葩问题。