Android 实现自定义属性 declare-styleable扩展 方法 &Eclipse/AndroidStudio xml 工具空间声明注意点

Android 实现自定义属性 declare-styleable扩展 方法 &Eclipse/AndroidStudio xml 工具空间声明注意点

自定义控件实现EditText输入 一键删除功能

参考:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0808/1643.html

实现步骤:

  • 1、 自定义LineEdittext 继承 EditText类
  • 2、 添加扩展属性 设置drawable left right Image图标
  • 3、 添加焦点监听接口、添加Edittext输入字符监听 onTounchEvent 重写
      import android.content.Context;
      import android.content.res.TypedArray;
      import android.graphics.Canvas;
      import android.graphics.Rect;
      import android.graphics.drawable.Drawable;
      import android.support.annotation.ColorRes;
      import android.support.annotation.DrawableRes;
      import android.support.annotation.IntegerRes;
      import android.text.Editable;
      import android.text.InputFilter;
      import android.text.InputType;
      import android.text.TextUtils;
      import android.text.TextWatcher;
      import android.text.method.PasswordTransformationMethod;
      import android.util.AttributeSet;
      import android.util.Log;
      import android.view.MotionEvent;
      import android.view.View;
      import android.widget.EditText;

      import ejiang.teacher.R;
      import ejiang.teacher.common.DisplayUtils;

      /**
      * Created by ejiang on 2017-03-31.
      *
      * @author Mr.Zang
      */

      public class LineEditText extends EditText implements TextWatcher,
           View.OnFocusChangeListener {

       private int color;
       private int status = 2;

       private Context mContext;
       /**
        * 是否获取焦点,默认没有焦点
        */
       private boolean hasFocus = false;
       /**
        * 手指抬起时的X坐标
        */
       private int xUp = 0;

       /*header--UnSelecte--*/
       private Drawable mLeftHender;
       /*header--Selecte*/
       private Drawable mLeftHenderSelete;
       /*belecte--Infromation_btn*/
       private Drawable del_btn;

       /*textsize*/
       @IntegerRes
       private int textsize;
       /*textcolor*/
       @ColorRes
       private int textColor;
       /*textHintColor*/
       @ColorRes
       private int textHintColor;

       @DrawableRes
       @ColorRes
       private int viewBackGround = R.drawable.bg_edittext;  //背景颜色
       @DrawableRes
       private int userHeaderUn = R.drawable.login_user;
       @DrawableRes
       private int userHeaderSel = R.drawable.login_user_seletor;




       public LineEditText(Context context, AttributeSet attrs) {
           super(context, attrs);
           mContext = context;
           init(attrs);
       }

       /**
        * 设置userHender图标
        *
        * @param userHender       --未选中or未获得焦点的Hender图标
        * @param userHenderSelect
        */
       public void setUserHender(@DrawableRes int userHender, @DrawableRes int userHenderSelect) {

           if (mContext != null) {
               this.mLeftHender = getLocalDrawbleRes(userHender);
               this.mLeftHenderSelete = getLocalDrawbleRes(userHenderSelect);
           }

       }

       private void init(AttributeSet attrs) {
           if (mContext != null && attrs != null) {
               TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.LineEditText);
               viewBackGround = a.getResourceId(R.styleable.LineEditText_editBackground, viewBackGround);
               userHeaderUn = a.getResourceId(R.styleable.LineEditText_userHeaderUn, userHeaderUn);
               userHeaderSel = a.getResourceId(R.styleable.LineEditText_userHenderSel, userHeaderSel);
               a.recycle();
           }


           //设置背景颜色 --样式
           setBackgroundResource(viewBackGround);
           /*设置删除按钮样式*/
           del_btn = mContext.getResources().getDrawable(R.drawable.login_delete);

           /*userHendler图标*/
           mLeftHender = getLocalDrawbleRes(userHeaderUn);
           mLeftHenderSelete = getLocalDrawbleRes(userHeaderSel);
           mLeftHender.setBounds(0, 0, mLeftHender.getMinimumWidth(), mLeftHender.getMinimumHeight());
           setCompoundDrawablesWithIntrinsicBounds(mLeftHender, null, null, null); //设置user图标

      //        setInputType(InputType.TYPE_CLASS_NUMBER); //设置输入模式 --数字
      //        setTransformationMethod(PasswordTransformationMethod.getInstance()); //设置输入不可见
      //        setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)}); //设置可输入的字符长度

      //        setHint(R.string.login_password); //设置hint提示
      //        setHintTextColor(mContext.getResources().getColor(R.color.color_no_year_book)); //设置hint颜色
      //        setTextSize(DisplayUtils.Px2Sp(mContext, 32)); //设置字体大小
      //        setCompoundDrawablePadding(DisplayUtils.Dp2Px(mContext, 10)); //设置Padding
           addListeners(); //设置监听
       }

       @Override
       protected void onDraw(Canvas canvas) {
           super.onDraw(canvas);
       }


       /**
        * 获取本地Drawble对象
        *
        * @param drawableRes
        * @return
        */
       private Drawable getLocalDrawbleRes(@DrawableRes int drawableRes) {
           return mContext.getResources().getDrawable(drawableRes);
       }


       // 处理删除事件
       @Override
       public boolean onTouchEvent(MotionEvent event) {
           if (del_btn != null && event.getAction() == MotionEvent.ACTION_UP) {
               // 获取点击时手指抬起的X坐标
               xUp = (int) event.getX();
               Log.e("xUp", xUp + "");
               /*Rect rect = new Rect();
               getGlobalVisibleRect(rect);
               rect.left = rect.right - 50;*/
               // 当点击的坐标到当前输入框右侧的距离小于等于getCompoundPaddingRight()的距离时,则认为是点击了删除图标
               if ((getWidth() - xUp) <= getCompoundPaddingRight()) {
                   if (!TextUtils.isEmpty(getText().toString())) {
                       setText("");
                   }
               }
           }
           return super.onTouchEvent(event);
       }


       /**
        * 添加监听回调
        */
       private void addListeners() {
           try {
               setOnFocusChangeListener(this);
               addTextChangedListener(this);
           } catch (Exception e) {
               e.printStackTrace();
           }
       }


       /**
        * 改变焦点监听
        *
        * @param focused
        * @param direction
        * @param previouslyFocusedRect
        */
       @Override
       protected void onFocusChanged(boolean focused, int direction,
                                     Rect previouslyFocusedRect) {
           super.onFocusChanged(focused, direction, previouslyFocusedRect);
           this.hasFocus = focused;
           if (focused) {
               setCompoundDrawablesWithIntrinsicBounds(mLeftHenderSelete, null, null, null);
               postInvalidate();
           } else {

           }

       }

       @Override
       protected void finalize() throws Throwable {
           super.finalize();
       }

       /**
        * 设置文字颜色
        *
        * @param color
        */
       public void setColor(int color) {
           this.color = color;
           this.setTextColor(color);
           invalidate();
       }


       //TextWatcher
       @Override
       public void afterTextChanged(Editable arg0) {
           postInvalidate();
       }

       @Override
       public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                     int arg3) {
           if (TextUtils.isEmpty(arg0)) {
               // 如果为空,则不显示删除图标
               setCompoundDrawablesWithIntrinsicBounds(mLeftHender, null, null, null);
           } else {
               // 如果非空,则要显示删除图标
               setCompoundDrawablesWithIntrinsicBounds(mLeftHenderSelete, null, del_btn, null);
           }
       }

       @Override
       public void onTextChanged(CharSequence s, int start, int before, int after) {
           if (hasFocus) {
               if (TextUtils.isEmpty(s)) {
                   // 如果为空,则不显示删除图标
                   setCompoundDrawablesWithIntrinsicBounds(mLeftHender, null, null, null);
               } else {
                   // 如果非空,则要显示删除图标
                   setCompoundDrawablesWithIntrinsicBounds(mLeftHenderSelete, null, del_btn, null);
               }
           }
       }


       //View.onFocusChangeListener
       @Override
       public void onFocusChange(View arg0, boolean arg1) {
           try {
               this.hasFocus = arg1;
           } catch (Exception e) {
               e.printStackTrace();
           }
       }

      }

declare-styleable 设置 res/value/attrs.xml

<declare-styleable name="LineEditText">
  <attr name="editBackground" format="reference"/>
  <attr name="userHeaderUn" format="reference"/>
  <attr name="userHenderSel" format="reference"/>
  <attr name="delteInformation" format="reference"/>
  <attr name="edithint" format="string|reference"/>
  <attr name="edithintColor" format="integer|reference"/>
</declare-styleable>

xml 根布局命名:

    原文作者:MrZang
    原文地址: https://www.jianshu.com/p/476cab45ac95
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞