自定義輸入框Java代碼
public class ForbidEmojiEditText extends android.support.v7.widget.AppCompatEditText {
private int mShowMaxLength;
private static final int MAX_LENGTH = 5;
public ForbidEmojiEditText(Context context) {
super(context);
}
public ForbidEmojiEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mShowMaxLength = MAX_LENGTH;
if (attrs != null) {
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ForbidEmojiEditText);
mShowMaxLength = arr.getInt(R.styleable.ForbidEmojiEditText_edtShowMaxLength, MAX_LENGTH);
arr.recycle();
}
setFilters();
}
public ForbidEmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mShowMaxLength = MAX_LENGTH;
if (attrs != null) {
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ForbidEmojiEditText);
mShowMaxLength = arr.getInt(R.styleable.ForbidEmojiEditText_edtShowMaxLength, MAX_LENGTH);
arr.recycle();
}
setFilters();
}
public void setFilters() {
InputFilter emojiFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
Pattern emoji = Pattern.compile(
"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher emojiMatcher = emoji.matcher(source);
if (emojiMatcher.find()) {
return "";
}
return null;
}
};
super.setFilters(new InputFilter[]{emojiFilter, new InputFilter.LengthFilter(mShowMaxLength)});
}
}
attrs.xml
<declare-styleable name="ForbidEmojiEditText">
<attr name="edtShowMaxLength" format="integer"/>
</declare-styleable>
view
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.***.ForbidEmojiEditText
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_50_dp"
android:background="@null"
android:textColor="@color/gray"
android:textColorHint="@color/line_border"
android:textSize="@dimen/text_size_small"
app:edtShowMaxLength = "20"/>
ok,剩下的工作就是把它像EditText一樣去應用吧