我到处搜索,但找不到解决方案。
我在 ScrollView 中有一个 View (我们称之为 myView)。 myView 比屏幕大。由于我能够获得我的手指在 myView 内的相对 x,y 位置,因此我希望在我的手指进入某个顶部/底部阈值时使 scrollView 自动滚动到顶部/底部。 我有一些想法,即将拖动位置转换为屏幕位置,但这并没有解决这个问题。
提前致谢
干杯
最佳答案
好吧,我自己想出来的。
首先,我必须扩展 ScrollView 类并添加一个接口(interface) OnScrollViewListener。
public class MyScrollView extends ScrollView {
private OnScrollViewListener mListener;
public MyScrollView(Context c, AttributeSet attrs) {
super(c, attrs);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mListener != null) {
mListener.onScrollChanged((OnScrollViewListener) this);
}
}
public void setOnScrollViewListener(OnScrollViewListener listener) {
mListener = listener;
}
public static interface OnScrollViewListener {
public void onScrollChanged(OnScrollViewListener listener);
}
}
接下来,在我的 Activity 中,我插入了一个成员 mScrollDistance,它指示 用户滚动的像素。
public class ScrollActivity extends Activity {
private int mScrollDistance;
@Override
protected void OnCreate(...) {
...
final MyScrollView myScrollView = (MyScrollView) findViewById(R.id.scroll_view);
myScrollView.setOnScrollViewListener(new MyScrollView.OnScrollViewListener() {
public void onScrollChanged(OnScrollViewListener listener) {
mScrollDistance = listener.getScrollY();
}
}
// making an drag and drop in an view that is inside the MyScrollView
final LinearLayout myLayout = (LinearLayout)findViewById(R.id.linear_layout);
myLayout.setOnDragListener(new View.OnDragListener() {
public boolean onDrag (View v, DragEvent event) {
int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED: {
}
case DragEvent.ACTION_DRAG_LOCATION: {
int y = Math.round(event.getY());
int translatedY = y - mScrollDistance;
int threshold = 50;
// make a scrolling up due the y has passed the threshold
if (translatedY < threshold) {
// make a scroll up by 30 px
myScrollView.scrollBy(0, -30);
}
// make a autoscrolling down due y has passed the 500 px border
if (translatedY + threshold > 500) {
// make a scroll down by 30 px
myScrollView.scrollBy(0, 30);
}
// listen for more actions here
// ...
}
}
}
}
现在,mScrollDistance 始终获得一个新值,拖动位置将转换为 View 位置。 我对此进行了测试,它适用于大于屏幕尺寸的布局/ View 。
希望对您有所帮助。
关于android - 在 Android 中通过拖放使 scrollView 自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352236/