Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set width/height for any widget through Theme in Android

Tags:

android

themes

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

My Problem is

If I define layout width/height also in styles and simply giving style="@style/myButtonStyle" for button in xml is working fine even though I did n't mention width/height in xml (might be inheriting from Style).

If I give width/height in xml without style prop and simply giving my Custom theme to activity is bringing all styles I specified in theme. But I did n't mention width/height in xml it is raising an exception saying that u have specify layout width/height, which I already specified in style itself.

my theme file is

 <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 is

 <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 specified dimension as

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

and I used like 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 is giving exception saying specify layout width, which I mentioned in button222 style and trying to use through my theme.

like image 514
Ganesh K Avatar asked Sep 07 '11 06:09

Ganesh K


2 Answers

You should insert a dimension value within the style xml:

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

Then you simply should reference the dimension value. So in your layout file you'll write:

android:layout_height="@dimen/buttonHeight"
like image 147
alessio.cocciolo Avatar answered Oct 19 '22 01:10

alessio.cocciolo


Just reference the style via app theme and this error will disappear. Do it like so:

style="@style/Theme.blue"
like image 20
Droid Chris Avatar answered Oct 19 '22 02:10

Droid Chris