简体   繁体   中英

How to layout a view that count margin from it's center instead of top-left on Android?

Say I have a image icon, I'd like to set the distance between the center of the icon and the left side of it's parent view to 20dp, the size of the icon may changes. How could I implement this?

It's something like the CenterX in iOS constraint, when you create a constraint, you can choose if from Leading, Trailing or CenterX. But I can't find anything similar on Android.

Updated: See the image below, the icons inside the red rect, I want to make the distance from the centerX to the left side of the window to 20dp. marginLeft count from left side of the icon, the not what I want. I do have solutions like fix all the icons to same size, or wrap icon inside another ViewGroup and make the ViewGroup size fixed, just curious if there's some way like the centerX constraint on iOS. 在此处输入图片说明

This looks like it's part of a list, so I will assume you have a single icon in your layout.

FrameLayout that is 40dp wide with icon centered

    <FrameLayout
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="-8dp">
        <ImageView
            android:layout_gravity="center_horizontal"/>
    </FrameLayout>

If the 40dp wrapper is too wide, put a negative right margin to reduce it (shown).

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