ScrollView可实现控件在超出屏幕范围的情况下滚动显示。
用法:在XML文件中将需滚动的控件包含在ScrollView中,当控件超出屏幕范围时可通过滚动查看
布局文件:
<LinearLayout 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"
android:orientation="vertical">
<Button
android:id="@+id/up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UP"
/>
<Button
android:id="@+id/down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOWN"
/>
<ScrollView
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
>
<TextView
android:id="@+id/content"
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
MainActivity:
package com.example.lowp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private TextView textView;
private ScrollView scrollView;
private Button but_up;
private Button but_down;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but_up = (Button)findViewById(R.id.up);
but_up.setOnClickListener(this);
but_down = (Button)findViewById(R.id.down);
but_down.setOnClickListener(this);
textView = (TextView)findViewById(R.id.content);
textView.setText(getResources().getString(R.string.content));
scrollView = (ScrollView)findViewById(R.id.scroll);
scrollView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
/**
* (1)getSrcollY()——滚动条滑动的距离
*
*/
//顶部状态
if(scrollView.getScrollY() <= 0){
Log.i("main", "顶部");
}
//底部状态
//TextView的总高度 <= 屏幕高度 + 滚动条的滑动距离
if(scrollView.getChildAt(0).getMeasuredHeight() <= scrollView.getHeight() + scrollView.getScrollY()){
Log.i("main", "底部");
Log.i("main", "TextView的总高度 = " + scrollView.getChildAt(0).getMeasuredHeight() + " 屏幕高度 = " + scrollView.getHeight() + " 滚动条的滑动距离 = " + scrollView.getScrollY()) ;
Toast.makeText(MainActivity.this, "底部", 1).show();
textView.append(getResources().getString(R.string.content));
}
break;
}
return false;
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
/**
* scrollTo:始终以滚动试图起点位置开始计算
* scrollBy:以上一次滚动试图的位置开始计算
*/
case R.id.up:
scrollView.scrollBy(0, -30);
break;
case R.id.down:
scrollView.scrollBy(0, 30);
break;
}
}
}
运行效果: