kotlin 如何在ToggleGroup中将图标切换为文本?

uhry853o  于 2023-04-12  发布在  Kotlin
关注(0)|答案(1)|浏览(121)

MaterialButtonToggleGroup与4 MaterialButton和水平方向.一些设备的屏幕不能显示所有按钮在行.因此,我想只显示图标,但为选定的按钮添加文本.这是可能的样式?最好是动画.
现在:

目标:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/rename_toggle_group"
    style="@style/CustomButtonToggleGroup"
    android:orientation="horizontal"
    android:layout_marginTop="@dimen/view_indent_vertical_min"
    android:gravity="center"
    app:checkedButton="@id/rename_current"
    app:selectionRequired="true"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/rename_current"
        android:minWidth="0dp"
        style="@style/MaterialButtonSecondaryToggle"
        app:icon="@drawable/ic_general"
        android:text="Current" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/rename_top"
        android:minWidth="0dp"
        app:icon="@drawable/ic_general"
        style="@style/MaterialButtonSecondaryToggle" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/rename_bottom"
        android:minWidth="0dp"
        style="@style/MaterialButtonSecondaryToggle"
        app:icon="@drawable/ic_general"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/rename_all"
        android:minWidth="0dp"
        style="@style/MaterialButtonSecondaryToggle"
        app:icon="@drawable/ic_general" />

</com.google.android.material.button.MaterialButtonToggleGroup>
5kgi1eie

5kgi1eie1#

我尝试了这个,并为我工作

private fun setupToggleGroup() {
    val (checkedButton, text) = getTogglePair(binding.renameToggleGroup.checkedButtonId)
    checkedButton?.text = text.toString()

    binding.renameToggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
        val (button, text) = getTogglePair(checkedId)
        button?.text = if (isChecked) text.toString() else ""
    }
}

private fun getTogglePair(checkedButtonId: Int): Pair<MaterialButton?, String?> {
    return when (checkedButtonId) {
        binding.renameCurrent.id -> Pair(binding.renameCurrent , getString(R.string.rename_current))
        binding.renameTop.id -> Pair(binding.renameTop , getString(R.string.rename_top))
        binding.renameBottom.id -> Pair(binding.renameBottom , getString(R.string.rename_bottom))
        binding.renameAll.id -> Pair(binding.renameAll , getString(R.string.rename_all))
        else -> Pair(null, null)
    }
}

在活动的onCreate中调用setupToggleGroup()

相关问题