xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/up_btn"
android:text="up"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/down_btn"
android:text="down"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<ScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="40sp"
android:text="@string/content"
/>
</ScrollView>
</LinearLayout>
getMeasuredHeight()和getHeight(),这两个方法都是获取组件高度的,在普通布局中,如果组件本身没有超过手机屏幕,那么这两个方法获取的组件高度相等;但是如果在像ScrollView这种滑动布局中,组件往往会超出屏幕,那么getHeight()获取的高度就是屏幕显示的高度,不确切的说就是屏幕高度,而getMeasuredHeight()获取的是这个组件实际大小,包括显示的部分和超出屏幕的部分。
getScrollY()表示ScrollView滑动的距离。开始滑动时获取的值为0。
package com.example.my.testexample;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.Toast;
/**
* Created by Administrator on 2017/10/26.
*/
public class Main2Activity extends Activity implements View.OnTouchListener,View.OnClickListener {
ScrollView scrollview;
Button up_btn, down_dtn;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acttivity_main2);
scrollview = (ScrollView) findViewById(R.id.scrollview);
scrollview.setOnTouchListener(this);
up_btn = (Button) findViewById(R.id.up_btn);
down_dtn = (Button) findViewById(R.id.down_btn);
up_btn.setOnClickListener(this);
down_dtn.setOnClickListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_UP:
{
if(scrollview.getScrollY()<=0)
{
Toast.makeText(this, "滑动到顶部", Toast.LENGTH_SHORT).show();
}
//如果滑动的距离+屏幕显示的高度>=组件的总高度
if(scrollview.getChildAt(0).getMeasuredHeight()<=scrollview.getScrollY()+scrollview.getHeight())
{
Toast.makeText(this, "滑动到底部", Toast.LENGTH_SHORT).show();
}
break;
}
}
return false;
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.up_btn:
{
scrollview.scrollBy(0,-30);
break;
}
case R.id.down_btn:
{
scrollview.scrollBy(0,30);
break;
}
}
}
}