先上效果图:
当滚动到底部时,自动加载更多内容。
解决思路:
1、TextView外嵌套一个ScrollView;
2、监听ScrollView的滚动事件;
3、判断手机是否滚动到底部
4、追加内容
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${packageName}.${activityClass}" > <ScrollView android:id="@+id/scroll" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="none" > <TextView android:id="@+id/text" android:lineSpacingExtra="8dp" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello_world" android:textSize="20dp" /> </ScrollView> </RelativeLayout>
Java代码
package com.example.scrollviewdemo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ScrollView; import android.widget.TextView; public class MainActivity extends Activity { private TextView textView; private ScrollView scrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); scrollView = (ScrollView) findViewById(R.id.scroll); textView.setText(getString(R.string.text)); scrollView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case MotionEvent.ACTION_MOVE: // getScrollY()是滚动条距离页面顶端的距离 // getMeasuredHeight()是屏幕顶端距离页面顶端的距离 // getHeight()是屏幕高度 int y = scrollView.getScrollY(); if (y <= 0) { Log.i("Main", "正在顶部"); } else if (scrollView.getChildAt(0).getMeasuredHeight() <= y + scrollView.getHeight()) { Log.i("Main", "已经滚动到底部"); Log.i("Main", "MeasuredHeight:" + scrollView.getMeasuredHeight() + ",ScrollY:" + y + ",Height:" + scrollView.getHeight()); // 追加内容 textView.append(getString(R.string.text)); } break; } return false; } }); } }