【Android -- UI 开发】EditText 的基本使用

本文详细介绍了Android中EditText的使用,包括基本属性如digits和inputType的设定,以及如何实现带有清除功能、下拉选项、自定义回车键功能、手机号码自动格式化和图标显示等功能。同时,提供了相应的代码示例。
摘要由CSDN通过智能技术生成

基本属性

EditText 官方文档

  • android:digits:指定特定能被输入的字符。

  • android:inputType:设定输入的类型,下面仅介绍一些常用的,多项可以使用“|”分割。
    textUri:必须是一个URL。
    textEmailAddress:Email地址
    textPassword:密码。
    number:数字。

  • android:numeric:指定数字输入类型,多项可以使用“|”分割。
    integer:数字。
    decimal:浮点类型。
    signed:带符号。

  • android:imeOptions=“actionSearch” & singLine=“true”
    actionNext下一步,通常用于跳转到下一个EditText
    actionGo前往,通常用于打开链接
    actionSend发送,通常用于发送信息
    actionSearch搜索,通常用于搜索信息
    actionDone确认,通常表示事情做完了

键盘挡住 EditText 的问题,解决方案:
在 EditText 所在的父布局设置 fitsSystemWindow=”true” 即可。

实例

一. 自带清除功能的 EditText

1. 效果图
image

2. 代码

/**
 * Created on 2019/6/5 10:12 AM
 *
 * @author GYQ
 */
@SuppressLint("AppCompatCustomView")
public class ClearEditText extends EditText implements View.OnFocusChangeListener, TextWatcher {
   
    private Drawable mClearDrawable;
    private boolean hasFocus;

    public ClearEditText(Context context) {
   
        this(context, null);
    }

    public ClearEditText(Context context, AttributeSet attrs) {
   
        super(context, attrs);
        init();
    }

    public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
   
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
   
        mClearDrawable = getCompoundDrawables()[2];
        if (mClearDrawable == null) {
   
            mClearDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_clear,null);
        }
        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
        setOnFocusChangeListener(this);
        addTextChangedListener(this);
        // 默认隐藏图标
        setDrawableVisible(false);
    }

    /**
     * 我们无法直接给EditText设置点击事件,只能通过按下的位置来模拟clear点击事件
     * 当我们按下的位置在图标包括图标到控件右边的间距范围内均算有效
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
   
        if (event.getAction() == MotionEvent.ACTION_UP) {
   
            if (getCompoundDrawables()[2] != null) {
   
                int start = getWidth() - getTotalPaddingRight() + getPaddingRight();
                int end = getWidth();
                boolean available = (event.getX() > start) && (event.getX() < end);
                if (available) {
   
                    this.setText("");
                }
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
   
        this.hasFocus = hasFocus;
        if (hasFocus && getText().length() > 0) {
   
            setDrawableVisible(true);
        } else {
   
            setDrawableVisible(false);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
   
        if (hasFocus) {
   
            setDrawableVisible(s.length() > 0);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
   
    }

    @Override
    public void afterTextChanged(Editable s) {
   
    }

    protected void setDrawableVisible(boolean visible) {
   
        Drawable right = visible ? mClearDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

}

3. 简单使用

<com.scarf.test.ClearEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

二、自带下拉功能的EditText

1. 效果图
image

2. 代码

/**
 * Created on 2019/6/5 10:31 AM
 *
 * @author Scarf Gong
 */
@SuppressLint("AppCompatCustomView")
public class DropEditText extends EditText implements PopupWindow.OnDismissListener, AdapterView.OnItemClickListener {
   
    private Drawable mDrawable;
    private PopupWindow mPopupWindow;
    private ListView mPopListView;
    private int mDropDrawableResId;
    private int mRiseDrawableResID;

    public DropEditText(Context context) {
   
        this(context, null);
    }

    public DropEditText(Context context, AttributeSet attrs) {
   
        super(context, attrs);
        init(context);
    }

    public DropEditText(Context context, AttributeSet attrs, int defStyle) {
   
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
   
        mPopListView = new ListView(context);
        mDropDrawableResId = R.drawable.ic_drop_down;
        mRiseDrawableResID = R.drawable.ic_drop_up;
        showDropDrawable(); // 默认显示下拉图标
        mPopListView.setOnItemClickListener(this);
    }

    /**
     * 我们无法直接给EditText设置点击事件,只能通过按下的位置来模拟点击事件
     * 当我们按下的位置在图标包括图标到控件右边的间距范围内均算有效
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
   
        if (event.getAction() == MotionEvent.ACTION_UP) {
   
            if (getCompoundDrawables()[2] != null) {
   
                int start = getWidth() - getTotalPaddingRight() + getPaddingRight();
                int end = getWidth();
                boolean available = (event.getX() > start) && (event.getX() < end);
                if (available) {
   
                    closeSoftInput();
                    showPopWindow();
                    return true;
                }
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
   
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
   
            mPopupWindow = new PopupWindow(mPopListView, getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOnDismissListener(this);
        }
    }

    private void showPopWindow() {
   
        mPopupWindow.showAsDropDown(this, 0, 5);
        showRiseDrawable();
    }

    private void showDropDrawable() {
   
        mDrawable = getResources().getDrawable(mDropDrawableResId);
        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], mDrawable, getCompoundDrawables()[3]);
    }

    private void showRiseDrawable() {
   
        mDrawable = getResources().getDrawable(mRiseDrawableResID);
        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], mDrawable, getCompoundDrawables()[3]);
    }

    public void setAdapter(BaseAdapter adapter) {
   
        mPopListView.setAdapter(adapter);
    }

    private void closeSoftInput() {
   
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   
        this.setText(mPopListView.getAdapter().getItem(position).toString());
        mPopupWindow.dismiss();
    }

    @Override
    public void onDismiss() {
   
        showDropDrawable();
    }

}

3. 简单使用

private void init() {
   
        dropEditText = (DropEditText) findViewById(R.id.drop_edit_text);
        String[] strings = new String[10];
        for (int i = 0; i < 10; i++) {
   
            strings[i] = "美女" + i + "号";
        }
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
        dropEditText.setAdapter(adapter);
    }

三、将软键盘回车换成搜索等按钮

1. 添加 imeOptions 属性:

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:imeOptions="actionSearch"
        android:singleLine="true"/>

注意: 这里一定还要设置 singLine=“true”,不然回车还是换行的功能。

2. 常见的属性

  • actionNext下一步,通常用于跳转到下一个EditText

  • actionGo前往,通常用于打开链接

  • actionSend发送,通常用于发送信息

  • actionSearch搜索,通常用于搜索信息

  • actionDone确认,通常表示事情做完了

四、EditText 输入自带空格的手机号码

1. 效果图
这里写图片描述
2. 布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="14dp"
        android:layout_marginRight="14dp"
        android:text="手机号码:"
        android:textSize="16sp"
        app:layout_constraintBaseline_toBaselineOf="@+id/editText"
        app:layout_constraintEnd_toStartOf="@+id/editText"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="81dp"
        android:ems="10"
        android:maxLength="13"
        android:inputType
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kevin-Dev

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值