xamarin android 自定義文本框簡單的用法
關鍵點在于,監聽EditText的内容變化,不同于java中文本内容變化去調用EditText.addTextChangedListener(mTextWatcher);為EditText設定内容變化監聽!
簡單來說就是添加一個AfterTextChanged 事件就OK了,這是最簡單的一種做法,當然你要想java那樣去監聽也可以的。
來看一下實作的效果圖:
自定義的EditText::CustomerEditText.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;
using Android.Util;
using Java.Lang;
using Android.Text;
using Android.Graphics;
namespace EditTextListener
{
public class CustomerEditText:EditText
{
private Drawable imgClear;
private Context Context;
public CustomerEditText(Context context, IAttributeSet attrs) : base(context, attrs)
{
this.Context = context;
init();
}
private void init()
{
imgClear = Context.Resources.GetDrawable(Resource.Drawable.del);
AfterTextChanged += (s, e) =>
{
setDrawable();
};
}
//回執删除圖檔
private void setDrawable()
{
if (Length() < 1)
SetCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
else
SetCompoundDrawablesWithIntrinsicBounds(null,null,imgClear,null);
}
//當觸摸範圍在右側時,觸發删除方法,隐藏叉叉
public override bool OnTouchEvent(MotionEvent e)
{
if (imgClear != null && e.Action == MotionEventActions.Up)
{
int eventX = (int)e.RawX;
int eventY = (int)e.RawY;
Rect rect = new Rect();
GetGlobalVisibleRect(rect);
rect.Left = rect.Right - 100;
if (rect.Contains(eventX, eventY))
{
Text=string.Empty;
}
}
return base.OnTouchEvent(e);
}
}
}
布局檔案Main.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">
<EditTextListener.CustomerEditText
android:id="@+id/edit_search"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="10dp"
android:background="@drawable/bg_frame_search"
android:hint="帶删除按鈕的EditText"
android:maxLength="50"
android:padding="5dp"
android:singleLine="true"
android:textColor="#000000" />
</LinearLayout>
自定義的背景樣式:bg_frame_search.xml
<?xml version="1.0" encoding="utf-8" ?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/background_white"/>
<corners android:radius="5dp"/>
<stroke android:width="1px" android:color="@color/frame_search"/>
</shape>
顔色值我就不貼了,自己寫幾個顔色就OK了。
代碼非常簡單,當然這是最簡單的實作方法,還有很多功能小功能都沒實作。是以後面繼續努力吧。