先看下效果:
1.介绍
在PDA开发中,经常会使用到文本框,但是Xamarin.Forms 版本4.2.x的不带清除按钮,本文章主要是自定义Entry按钮
2.开始
2.1 创建Xamarin.Forms项目过程省略
2.2 新建MyEntry.cs类,并集成Entry
namespace App1
{
public class MyEntry:Entry
{
}
}
2.3 在项目Android下新建MyEntryRender.cs类
[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRender))]
namespace App1.Droid
{
public class MyEntryRender:EntryRenderer
{
Drawable drawable;
public MyEntryRender(Context context) : base(context) {
drawable = GetDrawable("g_del_off20");
}
void ReseDelIcon(string text) {
if (!string.IsNullOrEmpty(text))
{
Control.SetCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null);
Control.SetOnTouchListener(new OnDrawableTouchListener());
}
else {
Control.SetCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null) {
ReseDelIcon(e.NewElement.Text);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control != null) {
if (e.PropertyName == "Text") {
Entry entry = (Entry)sender;
ReseDelIcon(entry.Text);
}
}
}
private BitmapDrawable GetDrawable(string imageEntryImage)
{
int resID = Resources.GetIdentifier(imageEntryImage, "drawable", Context.PackageName);
Android.Graphics.Drawables.Drawable drawable = ContextCompat.GetDrawable(Context, resID);
Bitmap bitmap = ((BitmapDrawable)drawable).Bitmap;
var im = new BitmapDrawable(Resources, Bitmap.CreateScaledBitmap(bitmap,20,20, true));
return im;
}
}
public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener {
public bool OnTouch(Android.Views.View v, MotionEvent e)
{
if (v is EditText && e.Action == MotionEventActions.Up) {
EditText editText = (EditText)v;
Drawable drawable = editText.GetCompoundDrawables()[2];
if (drawable != null) {
int width=editText.Width;
if (e.GetX()>= width - 30 && e.GetX()<= width-10) {
editText.Text = "";
return true;
}
}
}
return false;
}
}
}
2.4 在MainPage.xaml文件中,引用自定义控件
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:App1"
mc:Ignorable="d"
x:Class="App1.MainPage">
<StackLayout>
<!-- Place new controls here -->
<local:MyEntry x:Name="entry0"/>
<local:MyEntry x:Name="entry1"/>
<local:MyEntry x:Name="entry2"/>
</StackLayout>
</ContentPage>
请大家多多点赞,留言,多多赞赏!