How to set width / height for any widget using theme in Android

I need to use the same widgets (buttons, editext, textviews) with the same properties as width, height, textColor, size, etc. on multiple screens (xmls). So I created styles for individual widgets (one style for a button, one for editing text ...), and I defined all of these styles in my CustomTheme.

My problem

If I determine the width and height of the layout also in styles and just giving the style = "@ style / myButtonStyle" for the button in xml works fine, although I did not mention the width / height in xml (it can inherit from the style).

If I specify the width / height in xml without style support and just adding activity to my custom theme, all the styles specified in the theme. But I did not mention the width / height in xml, this throws an exception saying that u sets the width / height of the layout, which I already specified in the style itself.

My theme file

<style name="Theme.Blue" parent="android:Theme"> <item name="android:buttonStyle">@style/button222</item> <item name="android:textViewStyle">@style/text222</item> <item name="android:editTextStyle">@style/edittext222</item> </style> 

and my button222 style

  <style name="button222" parent="@android:style/Widget.Button"> <item name="android:layout_width">@dimen/mWidth</item> <item name="android:textColor">#F56266</item> <item name="android:textSize">20sp</item> </style> 

and I defined the size as

  <dimen name="mWidth">180dip</dimen> 

and i used this in layout.xml

  <Button android:layout_width="180dip" android:layout_height="wrap_content" android:text="This is large text." /> <Button android:layout_height="wrap_content" android:text="This is regular text one" /> <Button style="@style/button222" android:layout_height="wrap_content" android:text="This is regular text." /> 

and it throws an exception by indicating the width of the layout I mentioned in the button222 style and trying to use my theme.

+6
source share
3 answers

You should insert the size value in xml style:

 <dimen name="buttonHeight">40px</dimen> 

Then you just need to specify the dimension value. Therefore, in your layout file, you will write:

 android:layout_height="@dimen/buttonHeight" 
+10
source

Not sure what your goal is: is it important for you not to mention layout_width and layout_height in the layout_height file, or are you just looking for some way to use the values ​​from the theme without referring to the individual style?

In the latter case, the solution will be

 layout_width="?attr/myCustomWidth" 

where in your CustomTheme you defined the attribute myCustomWidth .

0
source

Just specify the style through the application theme and this error will disappear. Do it like this:

 style="@style/Theme.blue" 
0
source

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


All Articles