Search code examples
androidbuttonprogrammatically-created

Setting button style programmatically


I'm trying to create layout with buttons and spinners programmatically. I can't do this in xml, because number of spinners depends on certain parameters.

My question here is: how can i set button style from @style resources? It just need to be set once, when layout is created.

My code for creating button (class: DBsetupLayout):

RelativeLayout.LayoutParams doneButtonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    doneButton = new Button(this.context);
    doneButtonParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 1);
    doneButton.setLayoutParams(doneButtonParams);
    doneButton.setText("DONE");
    doneButton.setId(2);

I haven't found any addRule options to add style.

MainActivity contains this code:

DBsetupLayout setupLayout = new DBsetupLayout(this, activityStatesNumber);
btdevSetupSaveButton = setupLayout.doneButton;
btdevSetupSaveButton.setOnClickListener...

I tried this: android set style in code, but it doesn't work for me, so i'm looking for some kind of other solution.

Any help appreciated.

Regards


Solution

  • You can set button background.

    Using this code.

    button.setBackgroundResource(R.drawable.new_button_drawable);