I just can't center (vertically and horizontally) text in a Button I defined in styles.xml (works properly when all attributes are in layout)
Originally all attributes were set directly in the layout, but I have lots of fragments where all buttons are the same. When Button is fully declared in the layout I don't even need to specify a "gravity" value, text is automaticaly centered.
I tried to create a style for some attributes but I lost text centering and "android:gravity="center"" does not work, in the style and/or in the layout
styles.xml
<!-- GENERAL - BUTTON -->
<style name="Widget.AppCompat.Button.one_line">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">50dp</item>
<item name="android:paddingStart">20dp</item>
<item name="android:paddingEnd">20dp</item>
<item name="android:paddingBottom">20dp</item>
<item name="android:fontFamily">@font/roboto_condensed_bold</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/white</item>
<item name="android:textSize">@dimen/default_text_size</item>
<item name="android:gravity">center_vertical</item>
</style>
myLayout.xml
<android.support.constraint.ConstraintLayout>
...
<Button
android:id="@+id/btn_back"
style="@style/Widget.AppCompat.Button.one_line"
android:background="@drawable/border_green_full"
android:text="@string/retour"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<android.support.constraint.ConstraintLayout>
I would expect the text vertically centered. What am I missing ?
In your case just remove the:
<item name="android:paddingBottom">20dp</item>
Better use a parent style:
<style name="Widget.AppCompat.Button.one_line" parent="@style/Widget.AppCompat.Button">
...
</style>
The default value in this case is:
<item name="android:gravity">center_vertical|center_horizontal</item>
In general:
Originally all attributes were set directly in the layout, but I have lots of fragments where all buttons are the same
If you would like to centralize the style for all the buttons in your app, avoiding to specify the style
attribute in any buttons in the layouts just use:
materialButtonStyle
attribute in your app theme:Something like:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
...
<item name="materialButtonStyle">@style/Widget.MaterialComponents.Button</item>
</style>
buttonStyle
attribute:Something like:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
...
<item name="buttonStyle">@style/Widget.AppCompat.Button</item>
</style>
If you would like to customize the style, define the parent
style with Widget.MaterialComponents.Button
/Widget.AppCompat.Button
.