滚动视图是指当拥有很多内容,屏幕显示不完全时,需要通过滚动来显示完整的视图
ScrollView的种类:
(1)水平滚动视图:HorizontalScrollView
(2)垂直滚动视图:ScrollView(我们默认的就是垂直滚动)
下面我们先来一个简单的例子(在文字多的屏幕无法显示的时候,把TextView控件嵌套在ScrollView里面实现滚动视图的效果):
布局文件:
<RelativeLayout xmlns:android="" xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ScrollView android:id="@+id/scroll" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" android:text="@string/content" /> </ScrollView> </RelativeLayout>java代码文件很简单只需要引入布局就行了(只要没有创建新布局,默认的就是)这里就不多写了。
隐藏ScrollView
(1) 标签属性:android:scrollbars="none"
(2) 代码设置:
setHorizontalScrollBarEnabled(false);隐藏横向ScrollView
setVerticalScrollBarEnabled(false);隐藏纵向ScrollView
setOnTouchListener的使用
判断ScrollView何时滑动到底部
public class MainActivity extends Activity {private TextView text;private ScrollView scroll;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);text = (TextView) findViewById(R.id.text);scroll = (ScrollView) findViewById(R.id.scroll);scroll.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch (event.getAction()) {case MotionEvent.ACTION_UP:break;case MotionEvent.ACTION_DOWN:break;case MotionEvent.ACTION_MOVE:/** (1)getScrollY()==滚动条滑动的距离* (2)getMeasuredHeight()* (3)getHeight()* *///顶部状态if (scroll.getScrollY() <= 0) {Log.i("main", "已经到到了顶部");}else if (scroll.getChildAt(0).getMeasuredHeight() <= scroll.getHeight() + scroll.getScrollY()) {Log.i("main", "已经到了底部");}break;}return false;}});}}
那么我们还可以在文字滑动到底部的时候,继续加载文字,我们只需要加这样一条代码就可以了:
text.append(getResources().getString(R.string.content));
那么我们还可以设定滚动的位置:
我们需要在布局中添加两个按钮"向上和向下",
然后在java代码中添加点击事件在点击事件中加入这样的两个方法:
scroll.scrollBy(0, -30);
scroll.scrollBy(0, 30);
后面的那个数值为正,则向下滚动,,数值为负,则向上滚动
代码下载地址:
闹里有钱,静处安身。