【发布时间】:2019-11-07 10:44:21
【问题描述】:
我的源代码在 Kotlin 中(与 Java 完全互操作)与 Android Studio 3.4.1。
我在动态创建的视图的绝对定位中遇到了一个严重的错误问题。我的相对布局是空的,没有视图。我已阅读所有与此相关的 Stack Overflow 问题,但对我没有任何帮助。
我已将代码减少到最低限度,只是为了向社区表达我的痛苦:
我的活动代码是
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mt = this.resources.displayMetrics
wScreen = mt.widthPixels // 1080 pixels
hScreen = mt.heightPixels // 1920 pixels
bt = Button(this)
myLayout.addView(bt) // MyLayoit is relative layout ID
bt.id = View.generateViewId()
bt.setBackgroundColor(Color.RED)
// % view height is 6,3% of screen heigth
bt.layoutParams = RelativeLayout.LayoutParams
(round(0.1786* wScreen).toInt(), //193 pixels
round(0.0633*hScreen).toInt()) // 122 pixels
// top button is 92,7% of height screen
bt.x = 0.0179F * wScreen // Left position: 19 pixels
bt.y = 0.927F * hScreen // Top position: 1780 pixels
} // On Create
} // Main Activity
我的相对布局 XML 为空:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=
"br.com.greatsolutions.paulo.yourcalcs.MainActivity">
</RelativeLayout>
模拟器的尺寸为 2392x1440,显示 30% 的高度切割更多 按钮下方的小边距。我知道,因为我把同一个按钮放在不同的位置。
我的手机尺寸是 1920x1080。它显示相同的屏幕
如果有人可以帮助我,那就太好了。我需要在我的应用中进行精确的动态定位...
更新 1: 我尝试使用 Frame Layout 而不是 Relative Layout 运行。没有成功。
更新 2:我发现了一个解决方案。这与我的预期不同,但它有效。坚持是发明之母。我没有注意到顶部的绿色小栏......
【问题讨论】:
标签: android kotlin layout dynamic