android - Android - Kotlin - 如何克服按钮的最小宽度限制?
问题描述
我正在尝试使用 minSdkVersion 19 或更高版本(测试手机具有 Android 8.0.0,API 26)使用 Kotlin 操作 android 按钮的宽度。当我尝试使按钮变小时,我发现它的宽度无法超过大约 200 像素以上的某个阈值。
这就是我创建和操作按钮的方式:
val button = Button(this)
button.width = btn_side // btn_side = 175
constraintLayout.addView(button)
我已经尝试过的。不同的布局:TableLayout、ConstraintLayout。我尝试将 textSize 设置为零,以防它干扰按钮宽度。或者用空字符串替换任何按钮文本。我尝试将零或 10px minWidth 应用于按钮。我玩过 setPadding 按钮方法。我试图通过 layoutParams 属性分配宽度。这些都没有帮助。
我错过了什么?
这是我的xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GameFieldActivity"
android:id="@+id/constraintLayout"
>
* UPD * 有人删除了一个可能有用提示的答案:可能有一种方法可以使用不同的按钮构造函数。可能有一种方法可以通过AttributeSet传递所需的按钮宽度。
解决方案
简短的回答:
val button = Button(this)
val layoutParams = ViewGroup.LayoutParams(
50, // you can set initial width here
ViewGroup.LayoutParams.WRAP_CONTENT
)
constraintLayout.addView(button, layoutParams)
一些细节:
// create a button
val button = Button(this)
// crate a layout params you want this button to be added to ViewGroup with
val layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
// add a button to ViewGroup with layout params
constraintLayout.addView(button, layoutParams)
// set initial width
button.layoutParams.width = 50
button.width = 50
// increase width of button for 10 with each click
button.setOnClickListener {
button.layoutParams.width += 10
button.width += 10
}
推荐阅读
- html - 动态呈现页面内容时,无法让页脚粘在底部
- python - 如何在 Python 的随机森林回归器中手动预测?
- python - 如何在 Refextract 上同时运行多个文件
- java - 用外键连接两个表 - Hibernate,SpringBoot
- haskell - 如何使用 cabal 在 ghcid 中运行测试套件?
- android - 为颤振项目添加firebase不起作用
- python - 打开 JSON 文件列表并将其存储在另一个列表中
- typescript - 如何正确等待 TypeScript 中的承诺
- javascript - SyntaxError:意外的标识符 (MAC)
- matlab - Julia 3D 曲面图,如 Matlab,对数比例的颜色图