【问题标题】:Odd Button Spacing in Xamarin Forms (Android) When Using a StackLayout使用 StackLayout 时 Xamarin 表单 (Android) 中的奇数按钮间距
【发布时间】:2019-10-02 04:17:40
【问题描述】:

在使用StackLayout 控件布局一系列Button 控件时,我观察到一些奇怪的间距行为。

使用以下 XAML:

<StackLayout Spacing="4">
    <Button Text="Option #1" />
    <Button Text="Option #2" />
    <Button Text="Option #3" />
</StackLayout>

在我的模拟器中生成以下内容:

请注意,间距远大于指定的数量(4 个)。

现在,使用以下 XAML:

<StackLayout Spacing="4">
    <Button BackgroundColor="LightPink" Text="Option #1" />
    <Button BackgroundColor="LightBlue" Text="Option #2" />
    <Button BackgroundColor="LightGreen" Text="Option #3" />
</StackLayout>

在我的模拟器中生成以下内容:

在这里,间距看起来更正确(而且确实是)。

有人可以解释为什么非彩色按钮的显示方式如此吗?

【问题讨论】:

标签: android xamarin.forms


【解决方案1】:

该间距是按钮的 Android 默认可绘制背景的一部分。

您可以通过更改颜色来移除它,因为它会替换背景。正如你刚才所做的那样。

如果您想在不显式更改颜色的情况下删除空格,您可以在 styles.xml 文件的 Android 项目中设置主题并使用按钮中的 Android 颜色,如下所示:

<style name="NoPaddingButton" parent="android:Widget.Material.Button">
   <item name="android:layout_margin">0dip</item>
   <item name="android:background">@color/button_material_light</item>
</style>

然后将此样式添加到主题,通常称为MainTheme.Base

<item name="android:buttonStyle">@style/NoPaddingButton</item>

边距是this答案的一部分。

唯一的问题是上面会删除回放效果(点击按钮时看到的效果)。

要找回它,您可以按照以下步骤操作:

在 Drawable 文件夹中添加一个名为 button_gray_ripple.xml 的新 XML 文件并粘贴以下代码:

<?xml version="1.0" encoding="utf-8"?>
<!-- in drawable folder-->
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">

    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/button_material_light" />
        </shape>
    </item>
</ripple>

您之前创建的样式将如下所示:

<style name="MyButton" parent="android:Widget.Material.Button">
    <item name="android:layout_margin">0dip</item>
    <item name="android:background">@drawable/button_gray_ripple</item>
</style>

以上所有内容应如下所示:

【讨论】:

  • 我无法让涟漪的东西正常工作(应用程序不断抛出异常),而且由于我对 Xamarin 相当 ,我没有花很多钱时间就可以了。此外,我可以从 Xamarin Forms 端设置按钮的背景颜色并避免所有这些。我已将您的解决方案标记为已接受的答案,因为它解释了与我最初的问题相关的情况。
猜你喜欢
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
相关资源
最近更新 更多