Search code examples
androidbuttonstyles

Apply button style dynamically


I have a little trouble: I will create dynamically material buttons applying @style/Widget.AppCompat.Button.Borderless style. Obviously if I create buttons in xml file to static buttons it works fine, but in java code I don't know how do this. This is my code

  for (String nameCat : cat){
        Button button = new Button(getActivity());
        lP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dpToPx(60)); // dpToPx is convert method
        button.setLayoutParams(lP);

        // text button
        button.setText(nameCat);
        // add to linear layout
        lL.addView(button);
    }

Solution

  • if yu have your style in XML

     ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
        button = new Button(newContext);