0

I'm trying to set programatically style for my button. Here is my style:

   <style name="MainButton">
        <item name="android:background">@drawable/bg_button</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">70dp</item>
        <item name="android:padding">10dp</item>      
        <item name="android:textColor">@color/red</item>
        <item name="android:textSize">30sp</item>
        <item name="fontPath">fonts/Semibold.ttf</item>    

 
    </style>

And then in a fragment I try to do the following:

      val button = Button(ContextThemeWrapper(context, R.style.MainButton), null, R.style.MainButton).apply {
                    this.text = text
                }
llView.addView(button)

The button is added, but some of the settings specified in the style are not applied to it. For example, button height works like wrap_content, but expected 70 dp , no font is applied. However, if I use this style in .xml everything works well. Please, help me

P.S. I need to dynamically add buttons to view groups. Perhaps it is better to create a button in .xml with custom style and inflate it inside my code ? I need to dynamically add buttons on different screens, so I decided that it would be better to move the logic of creating buttons into a separate class, maybe it should be replaced with inflate, please help me.

testivanivan
  • 967
  • 13
  • 36
  • `layout_` attributes are part of the view's `LayoutParams`. Since you're creating the button in code and calling `addView()`, it will generate default params. You need to create them manually (or `inflate()` a layout instead, while being sure to specify the parent view). – Ben P. Nov 29 '21 at 16:15
  • @Ben P. ,Thanks for your answer, why isn't a custom font applied then? – testivanivan Nov 29 '21 at 16:21
  • what is this ?? `fonts/Semibold.ttf` – Noah Nov 29 '21 at 18:15
  • 1
    put the font in the where project fonts should be added and use `android:fontFamily="@font/the_font` to set the font – Noah Nov 29 '21 at 18:16

0 Answers0