嘿,只是想确定一个scrollview是否在android中向上或向下滚动。想要在向上滚动和向下滚动时执行不同的操作。
任何想法都表示赞赏, 感谢
答案 0 :(得分:4)
试试这个: 扩展Scrollview并覆盖onTouchEvent方法
private float mTouchPosition;
private float mReleasePosition;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mTouchPosition = event.getY();
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mReleasePosition = event.getY();
if (mTouchPosition - mReleasePosition > 0) {
// user scroll down
} else {
//user scroll up
}
}
return super.onTouchEvent(event);
}
答案 1 :(得分:1)
试试这个 创建customScrollView类并覆盖(修复某些情况)
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
Log.e(TAG, "new " + t + " old " + oldt);
if (t >= oldt) {
System.out.println("dwwn");
} else {
System.out.println("upppp");
}
}
答案 2 :(得分:1)
是的,你可以使用这个
scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
}
});
但是这需要minSdkVersion为23.所以要么你可以将minSdkVersion改为23或者创建一个这样的自定义滚动视图:
public class TouchDetectableScrollView extends ScrollView {
OnMyScrollChangeListener myScrollChangeListener;
public TouchDetectableScrollView(Context context) {
super(context);
}
public TouchDetectableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TouchDetectableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (myScrollChangeListener!=null)
{
if (t>oldt)
{
myScrollChangeListener.onScrollDown();
}
else if (t<oldt){
myScrollChangeListener.onScrollUp();
}
}
}
public OnMyScrollChangeListener getMyScrollChangeListener() {
return myScrollChangeListener;
}
public void setMyScrollChangeListener(OnMyScrollChangeListener myScrollChangeListener) {
this.myScrollChangeListener = myScrollChangeListener;
}
public interface OnMyScrollChangeListener
{
public void onScrollUp();
public void onScrollDown();
}}
在你的xml和java代码中使用TouchDetectableScrollView,然后像这样设置监听器:
scrollView.setMyScrollChangeListener(new TouchDetectableScrollView.OnMyScrollChangeListener() {
@Override
public void onScrollUp() {
//Toast.makeText(getActivity(), "Scrolling up", Toast.LENGTH_SHORT).show();
Log.d("scroll","up");
}
@Override
public void onScrollDown() {
// Toast.makeText(getActivity(), "Scrolling down", Toast.LENGTH_SHORT).show();
Log.d("scroll","down");
}
});
答案 3 :(得分:0)
尝试一下,对我有用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if(scrollY<=oldScrollY)
{
//scroll up
relativeLayout.setVisibility(View.VISIBLE);
}
else {
relativeLayout.setVisibility(View.GONE);}
}
});
}