首页 > 解决方案 > 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传递所需的按钮宽度。

标签: androidbuttonkotlinsize

解决方案


简短的回答:

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
}

推荐阅读