4

How to apply runtime button style in android kotlin?

My Style (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>

My Kotlin Code:

var btnOpt4 = Button(con)
btnOpt4 = rv.findViewById(R.id.btnOption4) as Button
Bharat Chauhan
  • 3,204
  • 5
  • 39
  • 52

3 Answers3

3

You can directly call by id to button ( by using apply plugin: 'kotlin-android-extensions')

in your activity and set style by this:

 button.setTextAppearance(R.style.AlertDialog_AppCompat)
abhilasha Yadav
  • 217
  • 1
  • 9
  • Welcome to StackOverflow! Although this might answer the question, consider supporting your answer with references and links on why/how it will work. – Rick M. May 23 '18 at 07:21
1

use below code

btn.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Medium);
rahul khurana
  • 188
  • 1
  • 9
  • 2
    Code only answers can almost always benefit from the addition of some explanation. In this case explain why you think this will fix the problem and where this code should be inserted. – Jason Aller Mar 04 '20 at 15:55
0
btnOpt4 = rv.findViewById<Button>(R.id.btnOption4)
btnOpt4.setTextAppearance(R.style.RedButtonLightTheme)

also you can use setBackgroundResource method to change background style of button in runtime:

btnOpt4.setBackgroundResource(R.drawable.some_drawable)
godot
  • 3,422
  • 6
  • 25
  • 42