Android_ScrollView的监听以及回到顶部

重写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);
            }
        });
    }
}
布局文件




    

    

    

        
        
    
    

    




你可能感兴趣的:(Android_ScrollView的监听以及回到顶部)