How to set a view at specific position on screen?

Viewed 219

How to can I set a view at a specific point on the screen programmatically? I want use a Point like x and y. I don't want it to translateX or translateY. I want for example to set a view to the Point x: 0 and y: 0 that means it needs to be at the top left of the screen. How can I achieve that?

I was trying this but the view translates X and Y what I don't want.

val layoutInflater = LayoutInflater.from(context)

val inflatedView: View = layoutInflater.inflate(R.layout.fragment_change_font_size_right, null, false)

inflatedView.popup_xml_view.x = 0f
inflatedView.popup_xml_view.y = 0f
2 Answers

Android had a layout that would support this requirements, but I think that it was pretty bad in regards to performance and it was deprecated (I hope that I am not wrong making this affirmation). However, the same behaviour can be implemented using a FrameLayout and add the views in that layout.

To add a view at a particular position, you create its layout params to set a width and a height, then set the margins which will position your view as absolute coordinates (the dimension is in pixels):

val imageView = ImageView(this)
imageView.setBackgroundResource(android.R.color.holo_red_dark)
imageView.layoutParams = FrameLayout.LayoutParams(width, height).apply {
    setMargins(left, top, right, bottom)
}
root.addView(imageView)

For a height/width of 200 and margins of (100, 100, 0, 0), it will look something like the image below (run on an emulated Pixel 3).

screenshot

NOTE: Here is a talk where they talk about this approach to emulate the AbsoulteLayout and why they "killed" it.

I found this to work:

ViewGroup.MarginLayoutParams margins = (ViewGroup.MarginLayoutParams) layout.getLayoutParams();
margins.topMargin = 100;
margins.leftMargin = 200;

Alternatively use animate:

view.animate().x(x).y(y).setDuration(0).start();
Related