0

I am trying to transfer an xml design to a design programmatically in java. But the code in java does not create the same result for me as in xml. How can I make it exactly the same?

xml:

<Button
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:text="next"
            app:backgroundTint="@color/purple_500" />

result

java:

int buttonStyle = R.style.Theme_Button;
        Button button = new Button( new ContextThemeWrapper(this, buttonStyle), null, buttonStyle);
        button.setId(R.id.centralized_btn_next);
        button.setOnClickListener(this);
        button.setLayoutParams(Components.createLayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM));
        button.setGravity(Gravity.CENTER);
        button.setText("next");
        button.setBackgroundResource(R.color.purple_500);
        rootLayout.addView(button);

Theme_Button:

 <style name="Theme.Button" parent="Widget.AppCompat.Button.Colored">
      
    </style>

result

I tried to search a lot on Google and to use chatGPT but I did not find a solution, the style is the same in both and the attributes. There are two differences in both the color and the style of the button. I think it's because the app theme (which is set in the minifest) doesn't apply to the java code, I tried setting setTheme. Apparently the values can be set as in the app's theme but it still won't help me know why it happened and what the solution is

editing: I've found that the button processes its shape due to setBackgroundResource. I'll try to find an alternative for that, but still, the question remains why the text color is different.

Mordechay
  • 21
  • 5
  • 1
    Regarding setting Tint, you can use setBackgroundTintList() method. You can readm more in this very old thread: https://stackoverflow.com/questions/29801031/how-to-add-button-tint-programmatically – basileus Aug 03 '23 at 06:29

0 Answers0