简体   繁体   中英

Why setY in a Framelayout not work?

I put an Imageview in a match_parent Framelayout, the Framelayout's visibility is GONE, then caculate the ImageView's coordinate and setX/Y then make the Framelayout VISIABLE. But the ImageView's layout position is weird!

The Code is simple:

override fun onVisibilityChanged(
    changedView: View?,
    visibility: Int) {

    if(visibility == View.VISIBLE && mTargetView != null){
        var location = intArrayOf(0,0)
        mTargetView?.getLocationOnScreen(location)

        var x = location[0] + mTargetView?.width!! / 2 - mIconWidth/2
        var y = location[1] - mIconHeight / 2 - mStatusBarH

        Log.d("lee","\nbefore x: ${mDelView.x}, y: ${mDelView.y}")
        /* 
         * use this code will get the right result.
        mLayoutParams.leftMargin = x
        mLayoutParams.topMargin = y
        */
        mDelView.x = x.toFloat()
        mDelView.y = y.toFloat()

        Log.d("lee","\nafter x: ${mDelView.x}, y: ${mDelView.y}")

    }

    super.onVisibilityChanged(changedView, visibility)
}

The log show the coordinate is correct:

lee: before x: 492.0, y: 332.0
after x: 492.0, y: 332.0

The layout position show the ImageView's layout position always at the left top corner. When use the picture bellow is using the LayoutParams margin and the layout position is right. It really confused me.

在此处输入图片说明 在此处输入图片说明

The layout position show the ImageView's layout position always at the left top corner

Because this is how FrameLayout works. You want to position container's childs by hand, use either RelativeLayout or write own container.

The View's layout bounds decided by the view's left, top, bottom, right position, relative to parent. The second phase of the layout mechanism will caculate these position.

/**
 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
 * {@link #setTranslationX(float) translationX} property to be the difference between
 * the x value passed in and the current {@link #getLeft() left} property.
 *
 * @param x The visual x position of this view, in pixels.
 */
public void setX(float x) {
    setTranslationX(x - mLeft);
}

The setX source code show this function only change the the visual x position of this view, and the mLeft value not change. So setX/Y will not change the layout positon.

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