从Xamarin Forms在Android上制作混合大小写按钮



我是Xamrin的新手。我正在尝试构建一个Xamarin Forms应用程序(尽可能少的原生应用程序(,用于在Android和IOS上运行。

我在Android Emulator中运行,按钮都有大写文本,即使我以混合大小写指定文本。

我发现了许多页面,上面写着向styles.xml添加以下内容:

<item name="android:textAllCaps">false</item>

另一个参考:

<item name="textAllCaps">false</item>

不过,根据styles.xml中的文档,似乎有一些更改,所以我添加了它,现在看起来是这样的:

<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
<!-- As of Xamarin.Forms 4.6 the theme has moved into the Forms binary -->
<!-- If you want to override anything you can do that here. -->
<!-- Underneath are a couple of entries to get you started. -->
<!-- Set theme colors from https://aka.ms/material-colors -->
<!-- colorPrimary is used for the default action bar background -->
<!--<item name="colorPrimary">#2196F3</item>-->
<!-- colorPrimaryDark is used for the status bar -->
<!--<item name="colorPrimaryDark">#1976D2</item>-->
<!-- colorAccent is used as the default value for colorControlActivated
which is used to tint widgets -->
<!--<item name="colorAccent">#FF4081</item>-->
<item name="textAllCaps">false</item>
<item name="android:textAllCaps">false</item>
</style>
</resources>

但当我运行模拟器时,它会显示所有大写的按钮文本。

我不知道还能尝试什么。

您可以为按钮创建自定义渲染器,并将SetAllCaps设置为false,然后重试。

这是代码:

public class CustomButtonRenderer : ButtonRenderer
{
public CustomButtonRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Cleanup
}
if (e.NewElement != null)
{
var button = (Button)this.Control; 
button.SetAllCaps(false);
}
}
}

我做了一个测试,发现问题与Xamarin.Forms的版本有关。

  • 如果您使用的是Xamarin.Forms 4.6,您之前提到的解决方案就可以了,我们只需要将<item name="android:textAllCaps">false</item>添加到style.xml中。

  • 如果您使用的是最新版本(4.8(,上面的解决方案不起作用,我们需要为按钮创建自定义渲染器,请将代码复制到您的android项目中。

    [assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(MyRenderer))]
    namespace YourNameSpace.Droid
    {
    class MyRenderer : ButtonRenderer
    {
    public MyRenderer(Context context) : base(context)
    {
    }
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
    base.OnElementChanged(e);
    if (e.OldElement != null)
    {
    // Cleanup
    }
    if (e.NewElement != null)
    {
    Control.SetAllCaps(false);
    }
    }
    }
    }
    

在xaml控件中使用TextTransform属性为None

最新更新