Android开发EditText小技巧

作者: 总会颠沛流离 | 来源:发表于2019-07-04 08:37 被阅读190次

    自带清除功能的 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);
    }
    

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

    添加 imeOptions 属性:

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

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

    常见的属性

    actionNext下一步,通常用于跳转到下一个EditText
    actionGo前往,通常用于打开链接
    actionSend发送,通常用于发送信息
    actionSearch搜索,通常用于搜索信息
    actionDone确认,通常表示事情做完了

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

    在android开发过程中,经常会要求用户输入手机号,为了便于观看,我们都会以150 xxxx xxxx这种格式展示。

    1.效果图

    image

    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="phone"
        android:hint="@string/mine_phone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="parent" />
        </android.support.constraint.ConstraintLayout>
    

    3.代码

    public class MainActivity extends AppCompatActivity {
    private EditText mPhoneNum;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
        initView();
    
        initData();
    
    }
    private void initView() {
        mPhoneNum = (EditText)findViewById(R.id.editText);
    }
    private void initData() {
        mPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence == null || charSequence.length() == 0) {
                    return;
                }
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0;i<charSequence.length();i++) {
                    if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                        continue;
                    } else {
                        stringBuilder.append(charSequence.charAt(i));
                        if ((stringBuilder.length() == 4 || stringBuilder.length() == 9)
                                && stringBuilder.charAt(stringBuilder.length() - 1) != ' ') {
                            stringBuilder.insert(stringBuilder.length() - 1, ' ');
                        }
                    }
                }
                if (!stringBuilder.toString().equals(charSequence.toString())) {
                    int index = start + 1;
                    if (stringBuilder.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    mPhoneNum.setText(stringBuilder.toString());
                    mPhoneNum.setSelection(index);
    
                }
            }
    
            @Override
            public void afterTextChanged(Editable editable) {
    
            }
        });
    }
    
    
    }
    

    相关文章

      网友评论

        本文标题:Android开发EditText小技巧

        本文链接:https://www.haomeiwen.com/subject/tkikhctx.html