[英]Add view at point on screen in LinearLayout
我正在尝试使用 LinearLayout 将视图动态添加到屏幕上不同点的视图中。 这是我试图将视图添加到的视图:
<LinearLayout
android:id="@+id/playerContainerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#B86262"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/scrollView2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/top_drawer" />
添加视图的代码(TextView):
fun addLabelToViewAtLocation(view:LinearLayout, x:Int, y:Int) {
var tv2 = TextView(this)
tv2.text = x.toString() + "," + y.toString()
tv2.setBackgroundColor(Color.WHITE)
var ll2 = LinearLayout.LayoutParams(
200,
60)
tv2.x = x.toFloat()
tv2.y = y.toFloat()
tv2.setLayoutParams(ll2)
view.addView(tv2,index)
view.requestLayout()
}
function 调用:
val pcv = this.findViewById<LinearLayout>(R.id.playerContainerView)
pcv.post{
addLabelToViewAtLocation(pcv,10, 10)
addLabelToViewAtLocation(pcv,0, 0)
addLabelToViewAtLocation(pcv,200, 60)}
因此正在添加文本视图,但它们没有出现在正确的位置 - 应该在左上角的0,0
文本视图出现在10,10
文本视图的右上角,因为它是首先添加的。
从表面上看,这奇怪地充当了相对布局而不是线性布局,但我只是找不到解决方法。
想法?
最终使用RelativeLayout
而不是LinearLayout
与 alignWithParent = true,更新添加视图 function:
fun addLabelToViewAtLocation(view: RelativeLayout, x:Int, y:Int, text:String) {
var tv = TextView(this)
tv.text = text
tv.setBackgroundColor(Color.WHITE)
var rl = RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT)
rl.alignWithParent = true
tv.x = x.toFloat()
tv.y = y.toFloat()
tv.setLayoutParams(rl)
view.addView(tv)
view.requestLayout()
}
无论我尝试什么,都无法使 LinearLayout 工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.