简体   繁体   中英

Xamarin.Forms: Remove padding inside Button

I want to have a small button. The height of the button is 30. On some plattforms (Android, UWP) the text inside the button is cut off. That's because there is a padding between the text and the outside border.

One option is to make the button bigger, but there is enough space for the text. Is there an option for setting the inside padding?

On Android, you can do this with styling.

Resources/values-v21/styles.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <style name="myTheme" parent="android:Theme.Material">
    <item name="android:buttonStyle">@style/noPaddingButtonStyle</item>
  </style>

  <style name="noPaddingButtonStyle" parent="android:Widget.Material.Button">
    <item name="android:paddingLeft">0dp</item>
    <item name="android:paddingRight">0dp</item>
  </style>
</resources>

AndroidManifest.xml

Set custom theme as application theme.

<application android:label="$safeprojectname$" android:theme="@style/myTheme"></application>

It's setting the left and right margin to 0dp . The default style has a padding.

This is working on Android >= 5. If you want to support lower android versions, you have to add multiple style folders and use other base themes like Theme.Holo or Theme.AppCompat .


Or you go for the Renderer:

using App6.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(Button), typeof(ZeroPaddingRenderer))]
namespace App6.Droid
{
    public class ZeroPaddingRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            Control?.SetPadding(0, Control.PaddingTop, 0, Control.PaddingBottom);
        }
    }
}

One option is to use a Label instead of a Button, and use a TapGestureRecognizer instead of Click events. The Label gives you more control over the layout of the text than a Button, but you don't get the advantage of it being translated into the native button control on each platform.

也许您可以使用FontSize来适应按钮HeightRequest ,除非您需要创建自定义渲染器来设置填充。

Now Xamarin allows you to do something like this, in XAML:

 <Button.Padding>
     <Thickness>0</Thickness>
 </Button.Padding>

Or in C#:

Button button = new Button();
button.Text = "Button";
button.Clicked += OnClicked;
button.Padding = new Thickness(0, 0, 0, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM