本文介绍滚动到底部或顶部响应(如加载更多)的ScrollView的使用。网上关于到达底部加载更多的listView示例很多,对于ScrollView却寥寥无几,下面介绍使用自定义的ScrollView来完成该功能的实例。
示例APK可从这些地址下载:Google Play, 360手机助手, 百度手机助手, 小米应用商店, 豌豆荚
示例代码地址见BorderScrollViewDemo,效果图如下:

1、引入公共库
引入TrineaAndroidCommon@Github(欢迎star和fork^_^)作为你项目的library(如何拉取代码及添加公共库),或是自己抽取其中的BorderScrollView@Github部分使用,BorderScrollView继承自ScrollView,可以自定义滚动到底部或顶部时需要完成的任务。
2、自定义layout
只需将定义的ScrollView标签换成cn.trinea.android.common.view.BorderScrollView标签即可,源码如下(其中的多个TextView只是为了将ScrollView撑满一屏幕):
layout xml源码
3、设置onTop和onBottom事件
通过borderScrollView.setOnBorderListener(OnBorderListener onBorderListener)设置到达底部和顶部的响应。
OnBorderListener有onTop()和void onBottom()两个函数可以实现,分别在滑动到顶部和底部时被调用执行。代码如下:
Java部分实现源码
Java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
public
class
BorderScrollViewDemo
extends
Activity
{
private
BorderScrollView
borderScrollView
;
private
TextView
textView1
;
private
TextView
textView2
;
private
Context
context
;
@Override
protected
void
onCreate
(
Bundle
savedInstanceState
)
{
super
.
onCreate
(
savedInstanceState
)
;
setContentView
(
R
.
layout
.
border_scroll_view_demo
)
;
context
=
getApplicationContext
(
)
;
borderScrollView
=
(
BorderScrollView
)
findViewById
(
R
.
id
.
scroll_view
)
;
borderScrollView
.
setOnBorderListener
(
new
OnBorderListener
(
)
{
@Override
public
void
onTop
(
)
{
// may be done multi times, u should control it
Toast
.
makeText
(
context
,
"has reached top"
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
}
@Override
public
void
onBottom
(
)
{
// may be done multi times, u should control it
Toast
.
makeText
(
context
,
"has reached bottom"
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
}
}
)
;
textView1
=
(
TextView
)
findViewById
(
R
.
id
.
text1
)
;
textView2
=
(
TextView
)
findViewById
(
R
.
id
.
text2
)
;
Display
display
=
getWindowManager
(
)
.
getDefaultDisplay
(
)
;
textView1
.
setHeight
(
display
.
getHeight
(
)
/
2
)
;
textView2
.
setHeight
(
display
.
getHeight
(
)
/
2
)
;
}
}
|
注意onTop和onBottom是有可能被多次执行的,需要自己控制,将在后面的实现原理中介绍具体原因~。
本文提供了一个自定义ScrollView实例,用于在滚动到底部或顶部时触发特定任务,包括示例代码和布局文件说明。适用于Android开发者。

1999

被折叠的 条评论
为什么被折叠?



