!这个问题不是关于创建边框,而是关于在创建边框时自定义它的长度!
我正在开发一个Xamarin Forms项目,我希望在Android设备上更改Entry字段下方边框的颜色。目前我已尝试使用自定义渲染器执行此操作,我几乎就在那里,但它并不像我希望的那样出现。蓝色底部边框比“输入”字段略宽/长,但在常规“输入”字段中,边框和“输入”字段的宽度/长度相同。如何自定义底部边框以适合“输入”字段的宽度/长度?
图片显示了顶部的常规Entry字段,以及底部的Entry with Custom Renderer。
Regular Entry field on top and Entry field with Custom Renderer at the bottom.
以下代码是用于在Android中本地创建底部边框的XML。
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="-2dp" android:left="-2dp" android:right="-2dp">
<shape>
<stroke android:color="#33b5e5" android:width="2dp"/>
</shape>
</item>
</layer-list>
以下代码是Entry的Custom Renderer
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using App.Company;
using App.Company.Droid;
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace App.Company.Droid
{
class CustomEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if(Control != null)
{
Control.SetBackgroundColor(Android.Graphics.Color.Lime);
Control.Background = Resources.GetDrawable(Resource.Drawable.BottomBorder, null);
}
}
}
}
以下代码是定义布局的XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App.Company;assembly=App.Company"
x:Class="App.Company.Views.StylesTestPage">
<ContentPage.Resources>
<ResourceDictionary>
<!-- COLORS -->
<Color x:Key="Rgray">#A8A8A8</Color>
<!-- ENTRIES -->
<Style x:Key="entryCustom"
TargetType="Entry">
<Setter Property="HorizontalOptions" Value="Center" />
<Setter Property="VerticalOptions" Value="Center" />
<Setter Property="WidthRequest" Value="200" />
<Setter Property="HeightRequest" Value="45" />
<Setter Property="BackgroundColor" Value="Transparent" />
</Style>
<Style x:Key="entryCustomGray"
TargetType="Entry"
BasedOn="{StaticResource entryCustom}">
<Setter Property="TextColor" Value="{StaticResource Rgray}" />
</Style>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<Entry Placeholder="Entry placeholder text"
Style="{StaticResource entryCustomGray}">
</Entry>
<local:CustomEntry Placeholder="In Shared Code"
Style="{StaticResource entryCustomGray}">
</local:CustomEntry>
</StackLayout>
</ContentPage.Content>
</ContentPage>
您需要在OnElementChanged中调用以下函数。
private void SetBorder(CustomEntry view)
{
if (view.HasBorder == false)
{
var shape = new ShapeDrawable(new RectShape());
shape.Paint.Alpha = 0;
shape.Paint.SetStyle(Paint.Style.Stroke);
Control.SetBackgroundDrawable(shape);
}
else
{
Control.SetBackground (originalBackground);
}
}