运行效果:

自定义EditText-2016917
自定义EditText1-2016917
自定义EditText2-2016917

先上代码,等会讲解:

自定义的EditTexT类如下:

public class CustomClearAndSearechEdittext extends EditText implements View.OnFocusChangeListener,TextWatcher{
private Drawable mClearDrawable;
/**
 * 控件是否有焦点
 */
private boolean hasFoucs;
public OnClickSearchListener mOnClickSearchListener;
public interface OnClickSearchListener{
    public void onClickSearch();
}
public void setOnClickSearchListener(OnClickSearchListener onClickSearchListener){
    this.mOnClickSearchListener=onClickSearchListener;
}
public CustomClearAndSearechEdittext(Context context) {
    this(context, null);
}

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

public CustomClearAndSearechEdittext(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}


private void init(final Context context) {
    //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
    final Drawable drawable = ContextCompat.getDrawable(context, R.drawable.abc_ic_clear_mtrl_alpha);
    setTextColor(getCurrentHintTextColor());
    mClearDrawable=drawable;
    mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth()+10, mClearDrawable.getIntrinsicHeight()+10);
    //默认设置隐藏图标
    setClearIconVisible(false);
    //设置焦点改变的监听
    setOnFocusChangeListener(this);
    //设置输入框里面内容发生改变的监听
    addTextChangedListener(this);
}



/**
 * 当手指抬起的位置在clean的图标的区域
 * 我们将此视为进行清除操作
 * getWidth():得到控件的宽度
 * event.getX():抬起时的坐标(该坐标是相对于控件本身而言的),可以理解成距离左边框的距离
 * getTotalPaddingRight():clean的图标左边缘至控件右边缘的距离
 * getPaddingRight():clean的图标右边缘至控件右边缘的距离
 * 于是:
 * getWidth() - getTotalPaddingRight()表示:
 * 控件左边到clean的图标左边缘的区域
 * getWidth() - getPaddingRight()表示:
 * 控件左边到clean的图标右边缘的区域
 * 所以这两者之间的区域刚好是clean的图标的区域
 */
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        if (getCompoundDrawables()[2] != null) {
            boolean searchable=event.getX()>((getWidth()-getPaddingRight()+80));
            boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                    && (event.getX() < ((getWidth() - getPaddingRight())));
            if (touchable) {
                this.setText("");
            }
            if(searchable&&mOnClickSearchListener!=null){
                Toast.makeText(getContext(),"search",Toast.LENGTH_SHORT).show();
                mOnClickSearchListener.onClickSearch();
            }
        }
    }

    return super.onTouchEvent(event);
}

/**
 * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
 */
@Override
public void onFocusChange(View v, boolean hasFocus) {
    this.hasFoucs = hasFocus;
    if (hasFocus) {
        setClearIconVisible(getText().length() > 0);
    } else {
        setClearIconVisible(false);
    }
}


/**
 * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
 * @param visible
 */
protected void setClearIconVisible(boolean visible) {
    Drawable right = visible ? mClearDrawable : null;
    setCompoundDrawables(getCompoundDrawables()[0],
            getCompoundDrawables()[1] ,right, getCompoundDrawables()[3]);

}


/**
 * 当输入框里面内容发生变化的时候回调的方法
 */
@Override
public void onTextChanged(CharSequence s, int start, int count,
                          int after) {
    if(hasFoucs){
        setClearIconVisible(s.length() > 0);
    }
}

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

}

@Override
public void afterTextChanged(Editable s) {

}

}

XML文件如下:

  <android.support.v7.widget.Toolbar
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:background="@color/themeColor"
    app:contentInsetStart="0.0dp"
    app:layout_scrollFlags="enterAlways|scroll"
    app:theme="@style/ToolbarStyle">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <android.support.design.widget.TextInputLayout
                android:id="@+id/search_til"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
                <com.jdk.gank.restapp.CustomizedWidget.CustomClearAndSearechEdittext
                    android:id="@+id/search_et"
                    android:hint="输入搜索内容"
                    android:inputType="text"
                    android:singleLine="true"
                    android:imeOptions="actionSearch"
                    android:paddingRight="70dp"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </android.support.design.widget.TextInputLayout>
            <ImageView
                android:id="@+id/search_iv"
                android:layout_width="30dp"
                android:layout_height="match_parent"
                android:src="@mipmap/search"
                android:gravity="center_vertical"
                android:textSize="25dp"/>
        </LinearLayout>
</android.support.v7.widget.Toolbar>

在fragment中使用:

 public class WatchAndShakeFragment extends Fragment implements CustomClearAndSearechEdittext.OnClickSearchListener{
@Bind(R.id.search_tv)
ImageView search_iv;
@Bind(R.id.search_til)
TextInputLayout textInputLayout;
@Bind(R.id.search_et)
EditText editText;
public static WatchAndShakeFragment newInstance(){
    if( watchAndShakeFragment ==null){
        watchAndShakeFragment =new WatchAndShakeFragment();
    }
    return watchAndShakeFragment;
}



public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if(v!=null){
        ButterKnife.bind(this,v);
        return v;
    }
     v=inflater.inflate(R.layout.fragment_watch_shake,container,false);
    ButterKnife.bind(this, v);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    actionBar= ((AppCompatActivity)getActivity()).getSupportActionBar();
  editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            ((CustomClearAndSearechEdittext)editText).setOnClickSearchListener(this);
            toolbar.setNavigationIcon(R.drawable.ic_back_28dp);
              toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      actionBar.setDisplayHomeAsUpEnabled(false);
                      toolbar.setNavigationIcon(null);
                      editText.setFocusable(false);
                      editText.setFocusableInTouchMode(false);
                  }
              });
    return v;
}
}
}

下面是讲解:

其实主要讲的就是CustomClearAndSearechEdittext类,在这个类中完成所有的功能,继承一个EditText,然后在EditText中设置图片,首先我们得到图片,然后我们调用mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth()+10, mClearDrawable.getIntrinsicHeight()+10);这个方法来提供画图片的画布,这个意思就是说,这个图片后面是画在这个地方的,值得注意是我们可以在这里设置图片的大小,但是不能设置图片的位置,比如,我这里就是在图片原来的基础上增加了10,之前我也一直想着在这里设置位置,但是行不通,然后我想着通过onDraw()重新将图片画上去,但是太麻烦,那么我们如何设置图片的位置呢?很简单,就是在xml里,因为我们的清除图片是在右侧,所以,我们设置android:paddingRight="70dp"来控制图片的位置,因为这个图片我们是通过

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

来显示的,主要就是 setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1] ,right, getCompoundDrawables()[3]);
也就是说,我们是将右边的图片画上去了,别的地方都没有图片,也就是说,这个图片其实是EditText中的,所以我们可以通过android:paddingRight="70dp"来控制图片的位置,这里清除图片设置好了,接下来,就是设置事件了,我们重写onTouchEvent(MotionEvent event)方法来设置事件,
在上面的代码的注释中已经写的很详细了,我就不写了,接下来就是设置搜索的事件了,由于搜索的按钮是在EditText中(由我们的布局知道),所以我们也需要通过重写onTouchEvent(MotionEvent event)方法来设置事件,也就是当我们按下的坐标大于搜索框到屏幕左边的距离时,就会触发onTouch事件,然后我设置了回调来处理这个事件。整个过程也解析完了,其实挺简单。