[英]How to set a view at specific position on screen?
How to can I set a view at a specific point on the screen programmatically?如何以编程方式在屏幕上的特定点设置视图? I want use a Point like x
and y
.我想使用像x
和y
这样的点。 I don't want it to translateX
or translateY
.我不想让它translateX
或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.例如,我想为 Point x: 0
和y: 0
设置一个视图,这意味着它需要位于屏幕的左上角。 How can I achieve that?我怎样才能做到这一点?
I was trying this but the view translates X and Y what I don't want.我正在尝试这个,但视图翻译了我不想要的 X 和 Y。
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
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). Android 的布局可以支持此要求,但我认为它在性能方面非常糟糕并且已被弃用(我希望我做出这个肯定没有错)。 However, the same behaviour can be implemented using a FrameLayout
and add the views in that layout.但是,可以使用FrameLayout
实现相同的行为并在该布局中添加视图。
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):要在特定的 position 添加视图,请创建其布局参数以设置宽度和高度,然后将 position 的边距设置为绝对坐标(尺寸以像素为单位):
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).对于 200 的高度/宽度和 (100, 100, 0, 0) 的边距,它将类似于下图(在模拟的 Pixel 3 上运行)。
NOTE: Here is a talk where they talk about this approach to emulate the AbsoulteLayout
and why they "killed" it.注意:这是一个谈话,他们讨论了这种模拟AbsoulteLayout
的方法以及他们“杀死”它的原因。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.