我的布局中有一个水平 ScrollView 。它包含一个线性布局(垂直方向),该布局又包含按钮。在此区域中,我可以水平滚动(在大多数手机中,这些按钮一次不能放在一个屏幕上)。 Android 为我提供了这种安慰。现在在这个水平 ScrollView 下方,有一个相对布局。
现在我想要的是,当我在相对布局中水平滑动时,我希望水平 ScrollView 中的按钮滚动。
我试图通过覆盖 onTouchEvent()
来实现这一点。问题在于,按钮会无限滚动(它们会超出屏幕)。我无法设定限制。我试图设定一个限制。但有些它是如何超过限制 1 并停止的。然后我无法滚动。
这是我的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusableInTouchMode="true" >
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/llt"
>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@drawable/button1"
style="@style/ButtonText"
android:text="Groups" />
<Button
android:id="@+id/login1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@drawable/button1"
style="@style/ButtonText"
android:text="QandA"/>
<Button
android:id="@+id/login2"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@drawable/button1"
style="@style/ButtonText"
android:text="Pending Requests"/>
<Button
android:id="@+id/login3"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@drawable/button1"
style="@style/ButtonText"
android:text="Settings"
></Button>
<Button
android:id="@+id/login4"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@drawable/button1"
style="@style/ButtonText"
android:text="Help"/>
</LinearLayout>
</HorizontalScrollView>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
.
.
.
这是我尝试过的:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
int x2 = (int) event.getRawX();
int y2 = (int) event.getRawY();
if(location1[0]<=leftconst&&(location2[0]+rightmost.getWidth())>=rightconst)
{
llt.scrollBy(currentX - x2 ,0);
}
currentX = x2;
currentY = y2;
break;
}
case MotionEvent.ACTION_UP: {
break;
}
}
return true;
}
leftconst
和 rightconst
分别等于 3 和 screenwidth
。但是当滚动它时它会停止两端。然后在那之后滚动是不可能的。 最左边
是id为login
的按钮,最右边
是id为login4
最佳答案
使用 scrollTo(x2)
代替 scrollBy
,这样滚动会更准确。使用 scrollBy 会使您的代码困惑。
scrollTo
的参数可以这样计算
final float ratio = horizontalscrollView_width/relativelayout_width;
然后在onTouch
scrollTo( x2 * ratio, 0);
成功完成滚动后,您可以使用VelocityTracker
实现fling 功能..
关于android - 从另一个 View 滚动一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12544537/