重写ScrollView
public class ObserveScrollView extends ScrollView {
private ScrollListener mListener;
public static interface ScrollListener {//声明接口,用于传递数据
public void scrollOritention(int l, int t, int oldl, int oldt);
}
public ObserveScrollView(Context context) {
super(context);
}
public ObserveScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ObserveScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// TODO Auto-generated method stub
super.onScrollChanged(l, t, oldl, oldt);
if (mListener != null) {
mListener.scrollOritention(l, t, oldl, oldt);
}
}
public void setScrollListener(ScrollListener l) {
this.mListener = l;
}
}
代码文件
package com.example.apptext;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private ObserveScrollView sc;
private Button but;
private LinearLayout ly;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化组件
sc = (ObserveScrollView) findViewById(R.id.sc);
ly = (LinearLayout) findViewById(R.id.ly);
but = (Button) findViewById(R.id.but);
//监听事件
sc.setScrollListener(new ObserveScrollView.ScrollListener() {
@Override
public void scrollOritention(int l, int t, int oldl, int oldt) {
if(t>100){
ly.setVisibility(View.VISIBLE);
}else{
ly.setVisibility(View.INVISIBLE);
}
}
});
//点击回到顶部事件
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//监听点击回到顶部
sc.scrollTo(0,0);
}
});
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.apptext.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#ff3600"
android:visibility="invisible"
android:id="@+id/ly"
android:orientation="vertical"
></LinearLayout>
<com.example.apptext.ObserveScrollView
android:id="@+id/sc"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="70dp"
android:src="@mipmap/ic_launcher"
/>
</LinearLayout>
</com.example.apptext.ObserveScrollView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/but"
android:text="置顶"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>