简体   繁体   中英

How to Center ImageView in HorizontalScroll View Android

I have been trying to center a large wallpaper of 3000px x 1500px (roughly) to when loaded show the center of the image and then the user can scroll left or right to view the rest. I have looked at a few examples and it doesn't seem to help it always lands on the left of the image!

I just need another pair of eyes to point me in the right direction.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/black">

   <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="none"
        >
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            >

            <ImageView
                android:id="@+id/imgFullscreen"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
  </HorizontalScrollView>
</RelativeLayout>

Thanks in advance!

first of all the layout inside the scroll view should be

 android:orientation="horizontal"

and wrap the content for both widht and height

Finally what you want is to start the activity with the scroll view at the center. You can programmatically do that with something like

int centerX = scrollView.getChildAt(0).getWidth()/2;
int centerY = scrollView.getChildAt(0).getHeight()/2;
scrollView.scrollTo(centerX, centerY);

for instance in the onCreateView of your Activity

首先,您需要将linearlayout和imageView的宽度设置为“ wrap_content”,然后测量 scollView并获取其宽度,之后,您需要获取屏幕尺寸 scrollTo ,然后滚动到中间

   middle Offset = (scrollView width - screen width ) / 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM