1.布局:activity_main.xml
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/bg"
android:layout_width="500dp"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@mipmap/ic_launcher" />
<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@mipmap/ic_launcher" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="220dp"
android:src="@mipmap/ic_launcher" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="220dp"
android:src="@mipmap/ic_launcher" />
</LinearLayout>
</HorizontalScrollView>
</FrameLayout>
2.activity实现:
java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView bg = findViewById(R.id.bg);
HorizontalScrollView hsv = findViewById(R.id.hsv);
hsv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
float canScrollX = hsv.getChildAt(0).getMeasuredWidth() - hsv.getMeasuredWidth();//计算hsv可滑动的距离X
float bgCanScrollX=bg.getMeasuredWidth()-hsv.getMeasuredWidth();//计算bg可滑动的距离X
float percent=scrollX/canScrollX;//计算滑动距离百分比
int bgSx= (int) (percent*bgCanScrollX);//bg滑动距离
bg.scrollTo(bgSx,scrollY);//bg滑动
Log.i(TAG,"canScrollX="+canScrollX+",bgCanScrollX="+bgCanScrollX+",percent="+percent+",bgSx="+bgSx);
}
});
}
}