How to add a custom element to an Android theme ad?

I have several custom themes in my .xml styles
Now that the activity accepts the theme, it uses the values colorPrimary , colorPrimaryDark, and colorAccent .
For my background layout am I using ? Attr / colorAccent , so it can choose the background color based on the selected theme.
If I use any of the above values, it works fine. But I want to determine the value of a custom item for my background color.
I tried like this below, but that didn't work. any ideas to make it work?
My custom theme with custom value:

<style name = "customTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">#4285f4</item> <item name="colorPrimaryDark">#2C75F2</item> <item name="colorAccent">#E1FFC7</item> <item name="customBgColor">#d3d3d3</item> </style> 


And I want to use it in a layout style, like

 <style name="layoutStyle" > <item name="android:background">?attr/customBgColor</item> </style> 
+5
source share
1 answer

Create the attrs.xml file shown in the image.

 <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Other values--> <attr name="customBgColor" format="reference" /> </resources> 

enter image description here

customTheme 1

 <style name = "customTheme1" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Other values--> <item name="customBgColor">#d3d3d3</item> </style> 

customTheme 2

 <style name = "customTheme2" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Other values--> <!-- Black Color in theme2--> <item name="customBgColor">#111111</item> </style> 

As an example, set the color in a TextView .

You can use it in the same way in any widget anywhere.

This TextView used in the next step.

 <TextView android:id="@+id/txt_rate_us_about" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Rate us on Play Store!" android:textColor="?attr/customBgColor" android:textSize="20dp" /> 

Want to set a theme dynamically.

 public class AboutUsActivity extends Activity { int theme = 1; // int theme = 2; 2nd theme. @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); switch (theme) { default: case 1: this.setTheme(R.style.customTheme1); break; case 2: this.setTheme(R.style.customTheme2); break; } // you must call `setTheme()` before `setContentView()` setContentView(R.layout.activity_about); } 

For several actions, you set a topic for each of them separately.

+12
source

Source: https://habr.com/ru/post/1257633/


All Articles