我有两个ScrollView
并排,通过使用下面的代码,我可以同时滚动它们但我仍然可以单独滚动它们,抛弃滚动位置。如何使每个视图同时滚动并禁用自己滚动每个视图?如果我的问题有任何混淆,我道歉。任何帮助将不胜感激,谢谢。
ScrollView sv1;
ScrollView sv2;
View clickSource;
View touchSource;
sv1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(touchSource == null)
touchSource = v;
if(v == touchSource) {
sv2.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP) {
clickSource = v;
touchSource = null;
}
}
return false;
}
});
sv2.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(touchSource == null)
touchSource = v;
if(v == touchSource) {
sv1.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP) {
clickSource = v;
touchSource = null;
}
}
return false;
}
});
答案 0 :(得分:2)
试试这个
sv1.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollX = sv1.getScrollX(); // for horizontalScrollView
int scrollY = sv1.getScrollY(); // for verticalScrollView
// DO SOMETHING WITH THE SCROLL COORDINATES
sv2.scrollTo(scrollX, scrollY);
}
});
答案 1 :(得分:2)
希望我能正确理解你的问题。如果你想同时滚动两个ScrollView
,那么下面的代码应该可以做到(未经测试):
首先创建一个界面来监听滚动事件:
public interface ScrollChangeListener {
public void onScrollChanged(View view, int x, int y, int oldx, int oldy);
}
接下来,创建一个自定义视图,以便您可以监听滚动更改:
public class ObservableScrollView extends ScrollView {
private ScrollChangeListener mScrollChangeListener;
public ObservableScrollView(Context context) {
super(context);
}
public ObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setScrollChangeListener(ScrollChangeListener listener) {
mScrollChangeListener = listener;
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
if (mScrollChangeListener != null) {
mScrollChangeListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
使用自定义视图并为ScrollView
创建一个侦听器。
ObservableScrollView mScrollView1;
ObservableScrollView mScrollView2;
...
ScrollChangeListener listener = new ScrollChangeListener() {
@Override
public void onScrollChanged(View view, int x, int y, int oldx, int oldy) {
ScrollView scrollView;
if (view == mScrollView1) {
scrollView = mScrollView2;
} else if (view == mScrollView2) {
scrollView = mScrollView1;
} else {
return;
}
scrollView.scrollTo(x, y);
}
};
...
mScrollView1.setScrollChangeListener(listener);
mScrollView2.setScrollChangeListener(listener);