判断滑动的是哪个scrollview

2024-12-04 03:34:49
推荐回答(1个)
回答1:

[mw_shl_code=java,true]public
class MyScrollView extends ScrollView {
public MyScrollView(Context
context, AttributeSet attrs) {
super(context,
attrs);

handler = new Handler() {

public void handleMessage(Message msg) {

if (msg.what == 1) {

/*这样做为什么可以成功?

*
认真思考它。如果思考明白了,尤其是getMeasuredHeight()与getHeight方法有什么区别,那么整个View的绘制过程可以说你就十分清晰。

*/
if
(view.getMeasuredHeight() <= getScrollY() + getHeight()

&& getScrollY() != 0) {

onScrollListener.onButtom();

} else if (getScrollY() == 0) {

onScrollListener.onTop();

} else

onScrollListener.onScroll();
}

}
};
//
对事件的处理一定是对view刻画完毕之后才开始的,所以,getHeight是有值的

setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent
event) {
view = getChildAt(0);

if (MotionEvent.ACTION_UP == event.getAction()) {

handler.sendEmptyMessage(1);

}
//return false与return
true 是有区别的,如果返回false,scrollview是不是有滑动的。百度一下这两个有什么区别就知道为什么要这么做了

return false;
}

});
}

public MyScrollView(Context context,
AttributeSet attrs, int defStyle) {
super(context, attrs,
defStyle);
// TODO Auto-generated constructor stub

}

private OnScrollListener onScrollListener;
private
Handler handler;
private View view;

public void
setOnScrollListener(OnScrollListener onScrollListener) {

this.onScrollListener = onScrollListener;

}
}
/*
*这个小demo只是为了展示如何判断用户滑动到了scrollview的位置。还有很多优化性能的方法,比如新开线程和将一些代码放在新的方法中,在Activity里面调用它!

*/[/mw_shl_code]
XML文件布局如下:[mw_shl_code=java,true]encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"
android:id="@+id/scrollView"
>

android:id="@+id/text"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

/>

[/mw_shl_code]
MainActivity的代码如下:
[mw_shl_code=java,true]public
class MainActivity extends Activity {
private MyScrollView
scrollView;
private TextView textView;
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

scrollView=(MyScrollView) findViewById(R.id.scrollView);

textView=(TextView) findViewById(R.id.text);
StringBuilder
s=new StringBuilder();
for(int i=0;i<150;i++){

s.append("这是一个scrollView的测试");

s.append("\n");
}
textView.setText(s);

scrollView.setOnScrollListener(new OnScrollListener() {

@Override

public void onTop() {

Log.e("OnTop", "OnTop");
}

@Override

public void onScroll() {

Log.e("OnScroll", "OnScroll");
}

@Override

public void onButtom() {

Log.e("OnButtom", "OnButtom");

}
});

}

}[/mw_shl_code]
OnScrollListener代码:[mw_shl_code=java,true]public
interface OnScrollListener {

public void
onButtom();
public void onTop();
public void
onScroll();

}
[/mw_shl_code]