Android: Placing a view in an arbitrary location

家住魔仙堡 提交于 2019-12-06 03:26:04

Not totally understanding what you're doing, it seems like you're making extra work for yourself by using RelativeLayout. What you're trying to place on screen isn't relative to anything, it's based on a specific coordinate in the image, so even if you use one of the other layouts you're still essentially placing something in absolute coordinates.

As for AbsoluteLayout being deprecated, from what I've read it's just to discourage it's use due to it's downsides relating to variable screen sizes. They have no intention of actually removing it, and even if they did you could just get the source and compile it into your project.

The solution is pretty ugly, it's not relative, but some may say it's plausible:

Adding a FrameLayout as a container (rather than the RelativeLayout noted below). The view to display is the child of that FrameLayout. In order to place it in place, add padding.

void addViewInAnArbitraryRect( Rect rect, 
                               Context context, 
                               View subjectView, 
                               View parent ) {
    FrameLayout container = new FrameLayout( context );
    parent.addView( container );
    container.setPadding( rect.left,
                          rect.top,
                          container.getWidth() - rect.right,
                          container.getHeight() - rect.bottom );
    container.addView( subjectView );

}

Note: You may want to adjust the coordinates of the page to the coordinates on screen. Just remember:

  1. Coordinates/width/height are not ready till onSizeChanged is called.
  2. Don't manipulate Views from onSizeChanged scope, or it may crop your view. Views do have to be manipulated from the context of the thread that created them. Use Handler for that.

I hoped it helped somebody.

Meymann

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!