Xamarin.Forms自定义渲染器,用于Android控件的.axml布局

时间:2016-10-27 19:29:05

标签: c# android xamarin xamarin.forms

我试图弄清楚如何在Xamarin.Forms中使用.axml布局文件作为自定义控件。任何人都可以提供在自定义渲染器中使用.axml文件的示例吗?例如,我想创建一个自定义Entry控件,(EnhancedEntry)。我希望它具有可配置的背景和边框颜色以及可配置的边框宽度。

我已经创建了背景形状,

drawable/enchancedEntryBackground.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <corners android:bottomLeftRadius="3dp" android:bottomRightRadius="3dp" android:topLeftRadius="3dp" android:topRightRadius="3dp" />
        <stroke android:width="0.5dp" android:color="@android:color/holo_blue_dark" />
        <solid android:color="@android:color/white" />
    </shape>

我在.axml文件中定义了一个布局,

layout/EnhancedEntry.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/enhancedEntry"
        android:background="@drawable/enhancedentrybackground" />
</LinearLayout>

给定一个自定义渲染器骨架和一个具有支持增强功能的类,是否可以使用xml和axml规范来创建新外观?

[assembly: ExportRenderer(typeof(EnhancedEntry), typeof(EnhancedEntryRenderer))]
namespace eSiteMobile.Droid.CustomRenderers
{

    public class EnhancedEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);            
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
        }        
    }
}

public class EnhancedEntry : Entry
    {
        public static BindableProperty BorderColorProperty = BindableProperty.Create(nameof(BorderColor), typeof(Color),
            typeof(EnhancedEntry), default(Color), defaultBindingMode: BindingMode.OneWay);

        public static BindableProperty BorderWidthProperty = BindableProperty.Create(nameof(BorderWidth), typeof(int),
            typeof(EnhancedEntry), default(int), defaultBindingMode: BindingMode.OneWay);

        public Color BorderColor
        {
            get { return (Color) GetValue(BorderColorProperty); }
            set { SetValue(BorderColorProperty, value); }
        }

        public int BorderWidth
        {
            get { return (int) GetValue(BorderWidthProperty); }
            set { SetValue(BorderWidthProperty, value); }
        }
    } 

1 个答案:

答案 0 :(得分:1)

您可以在MC中配置您正在谈论的媒体资源,将所呈现的OnElementChanged()称为Entry。它不在axml或xml中,但它仍然可能。

显然在VS的解决方案资源管理器中,您可以点击&#34;显示所有文件&#34;它将显示Control文件夹以添加自定义布局文件。我之所以说这显然是因为这对我不起作用,但如果你仍然希望在xml中使用它,那值得一试。

完成后,您应该能够引用您在Android.Resource.Layout方法中自定义视图的布局文件,但我发现在一个地方更容易完成所有操作!