简体   繁体   中英

Android: How to set horizontal scroll view image margins programmatically

I am creating a HorizontalScrollView in xml and inserting the images programmatically, but I am having trouble with margins. How do I set the horizontal margins for images in the HorizontalScrollView ? Below is my code:

xml:

<HorizontalScrollView
            android:id="@+id/HorizontalScrollView"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="15dp">

            <LinearLayout
                android:id="@+id/innerLay"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <!--Image Views here -->

            </LinearLayout>

</HorizontalScrollView>

java:

ImageView imageView = new ImageView(getActivity());
scrollLinearLayout.addView(imageView);
//set height and other image properties.

Use this function to set runtime margin to view

public static void setMargins (View v, int left, int top, int right, int bottom) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(left, top, right, bottom);
        v.requestLayout();
    }
} 

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