如何在android kotlin中运行时应用按钮样式

时间:2018-03-11 07:59:20

标签: android kotlin kotlin-android-extensions

如何在android kotlin中应用运行时按钮样式?

我的风格(themes.xml):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="WhiteButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorWhite</item>
        <item name="colorButtonNormal">@color/colorWhite</item>
        <item name="colorControlHighlight">@color/colorGray</item>
    </style>

    <style name="RedButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorRed</item>
        <item name="colorButtonNormal">@color/colorWhite</item>
        <item name="colorControlHighlight">@color/colorGray</item>
    </style>

    <style name="GreenButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorGreen</item>
        <item name="colorButtonNormal">@color/colorWhite</item>
        <item name="colorControlHighlight">@color/colorGray</item>
    </style>
</resources>

我的Kotlin代码:

var btnOpt4 = Button(con)
btnOpt4 = rv.findViewById(R.id.btnOption4) as Button

3 个答案:

答案 0 :(得分:2)

您可以直接通过ID拨打按钮  ( by using apply plugin: 'kotlin-android-extensions')

在您的活动中并通过此设置样式:

 button.setTextAppearance(R.style.AlertDialog_AppCompat)

答案 1 :(得分:0)

btnOpt4 = rv.findViewById<Button>(R.id.btnOption4)
btnOpt4.setTextAppearance(R.style.RedButtonLightTheme)

您也可以使用setBackgroundResource方法在运行时更改按钮的背景样式:

btnOpt4.setBackgroundResource(R.drawable.some_drawable)

答案 2 :(得分:-1)

使用以下代码

btn.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Medium);