效果图:
1 自定义控件CommonEditText.java代码:
package com.yiduoyun.cloudschool.view; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView.OnEditorActionListener; import com.yiduoyun.cloudschool.R; /** * * @ClassName: CommonEditText * @Description: 自定义的EditText,自带清空按钮(关于密码模式,需要设置password属性为TRUE,单纯设置inputType为textPassword不起作用) * @author gaoshunsheng [email protected] * @date 2014-3-6 下午1:44:30 * */ public class CommonEditText extends LinearLayout { private EditText editText; private ImageView imgClear; private TextWatcher textWatcher; private boolean isClearFunctionWork = true; public CommonEditText(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(getContext()).inflate( R.layout.layout_common_edit_text, this); editText = (EditText) findViewById(R.id.editText); imgClear = (ImageView) findViewById(R.id.imageView); imgClear.setVisibility(View.GONE); imgClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editText.setText(""); imgClear.setVisibility(View.GONE); } }); // 这里处理自定义的属性 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CommonEditText); // 设置默认文本 CharSequence hint = a.getText(R.styleable.CommonEditText_hint); editText.setHint(hint); // 设置文字大小 float textsize = a.getDimensionPixelSize(R.styleable.CommonEditText_textSize, -1); if(-1 != textsize) { editText.setTextSize(textsize); //这个很重要,根据TextView的setRawTextSize方法源代码获得 editText.getPaint().setTextSize(textsize); editText.invalidate(); } // 设置EditText文字颜色 ColorStateList textColor = a .getColorStateList(R.styleable.CommonEditText_textColor); if (null != textColor) { editText.setTextColor(textColor); } //设置EditText的Hint的文字颜色 ColorStateList textColorHint = a .getColorStateList(R.styleable.CommonEditText_textColorHint); if (null != textColorHint) { editText.setHintTextColor(textColorHint); } // 设置EditText是否单行显示 boolean singleLine = a.getBoolean( R.styleable.CommonEditText_singleLine, true); editText.setSingleLine(singleLine); // 设置InputType int inputType = a.getInt(R.styleable.CommonEditText_inputType, EditorInfo.TYPE_NULL); Log.i("InputType", inputType + ""); if(EditorInfo.TYPE_NULL != inputType) { editText.setInputType(inputType); } else { editText.setInputType(EditorInfo.TYPE_CLASS_TEXT); } //设置MaxLength属性 Integer maxLength = a.getInteger(R.styleable.CommonEditText_maxLength, 0); if(0 != maxLength) { InputFilter[] filters = {new InputFilter.LengthFilter(maxLength.intValue())}; editText.setFilters(filters); } // 设置清空按钮的宽高 int clearH = a.getDimensionPixelSize( R.styleable.CommonEditText_clearButtonHeight, -1); int clearW = a.getDimensionPixelSize( R.styleable.CommonEditText_clearButtonWidth, -1); if (-1 != clearH && -1 != clearW) { imgClear.setLayoutParams(new LayoutParams(clearH, clearW)); } // 设置按钮的Padding int padding = a.getDimensionPixelSize( R.styleable.CommonEditText_clearButtonPadding, -1); if (-1 != padding) { imgClear.setPadding(padding, padding, padding, padding); } //设置密码模式 boolean password = a.getBoolean(R.styleable.CommonEditText_password, false); if(password) { editText.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD); } //设置清空按钮图标 Drawable drawableClear = a.getDrawable(R.styleable.CommonEditText_drawableClearButton); if(null != drawableClear) { imgClear.setImageDrawable(drawableClear); } //设置清空按钮显示状态 boolean enableClearFunction = a.getBoolean(R.styleable.CommonEditText_enableClearFunction, true); isClearFunctionWork = enableClearFunction; //设置EditText监听 editText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(isClearFunctionWork) { toggleClearButton(s); } } }); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(isClearFunctionWork) { toggleClearButtonOnFocus(hasFocus); } } }); a.recycle(); } /** * 切换清空按钮 * * @param s */ private void toggleClearButton(CharSequence s) { if (s.length() > 0) { imgClear.setVisibility(View.VISIBLE); } else { imgClear.setVisibility(View.GONE); } } /** * 聚焦处理事件 * * @param onFocusChangeListener */ public void setOnFocusChangeListener( final OnFocusChangeListener onFocusChangeListener) { editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(isClearFunctionWork) { toggleClearButtonOnFocus(hasFocus); } onFocusChangeListener.onFocusChange(v, hasFocus); } }); } private void toggleClearButtonOnFocus(boolean hasFocus) { if (!hasFocus) { imgClear.setVisibility(View.GONE); } else if(hasFocus && editText.getText().length() > 0) { imgClear.setVisibility(View.VISIBLE); } } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { if(gainFocus) { editText.requestFocus(); } super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); } /** * 设置密码模式 */ public void setPasswordMode() { editText.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD); } /** * 编辑动作监听器,对键盘上的操作作监听 * * @param onEditorActionListener */ public void setOnEditorActionListener( OnEditorActionListener onEditorActionListener) { editText.setOnEditorActionListener(onEditorActionListener); } /** * 文本输入框内容改变事件 * * @param textWatcherImpl */ public void addTextChangedListener(TextWatcher textWatcherImpl) { this.textWatcher = textWatcherImpl; editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { textWatcher.onTextChanged(s, start, before, count); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { textWatcher.beforeTextChanged(s, start, count, after); } @Override public void afterTextChanged(Editable s) { if(isClearFunctionWork) { toggleClearButton(s); } textWatcher.afterTextChanged(s); } }); } public CommonEditText(Context context) { super(context); } /** * //设置清空按钮显示状态 * @param showClearButton */ public void showClearButton(boolean showClearButton) { imgClear.setVisibility(showClearButton ? View.VISIBLE : View.GONE); } /* * 返回EditText对象 */ public EditText getEditText() { return editText; } public int getSelectionStart() { return editText.getSelectionStart(); } public int getSelectionEnd() { return editText.getSelectionEnd(); } public void setSelection(int selection) { editText.setSelection(selection); } public void setText(CharSequence charSequence) { editText.setText(charSequence); } public CharSequence getText() { return editText.getText(); } public void setInputType(int inputType){ editText.setInputType(inputType); } /** * 设置文本输入框提示文本 * * @param hint */ public void setHint(String hint) { editText.setHint(hint); } /** * 设置清空按钮Drawable对象 * @param drawable */ public void setClearButtonDrawable(Drawable drawable) { imgClear.setImageDrawable(drawable); } }
2 布局代码layout_common_edit_text.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp" android:layout_gravity="center_vertical" android:gravity="center_vertical" android:orientation="horizontal" > <EditText android:id="@+id/editText" android:layout_weight="1" android:cursorVisible="true" android:focusable="true" android:focusableInTouchMode="true" android:textCursorDrawable="@null" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@null" /> <ImageView android:id="@+id/imageView" android:layout_weight="0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/delete" /> </LinearLayout>
3 在values文件夹下加入样式文件editText_attrs.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CommonEditText"> <!-- set editText hint --> <attr name="hint" format="string" /> <!-- set editText textSize --> <attr name="textSize" format="dimension" /> <!-- set editText textColor --> <attr name="textColor" format="reference|color" /> <!-- set editText textColorHint --> <attr name="textColorHint" format="reference|color" /> <!-- set editText inpuType --> <attr name="inputType"> <flag name="none" value="0x00000000" /> <flag name="text" value="0x00000001" /> <flag name="textCapCharacters" value="0x00001001" /> <flag name="textCapWords" value="0x00002001" /> <flag name="textCapSentences" value="0x00004001" /> <flag name="textAutoCorrect" value="0x00008001" /> <flag name="textAutoComplete" value="0x00010001" /> <flag name="textMultiLine" value="0x00020001" /> <flag name="textImeMultiLine" value="0x00040001" /> <flag name="textNoSuggestions" value="0x00080001" /> <flag name="textUri" value="0x00000011" /> <flag name="textEmailAddress" value="0x00000021" /> <flag name="textEmailSubject" value="0x00000031" /> <flag name="textShortMessage" value="0x00000041" /> <flag name="textLongMessage" value="0x00000051" /> <flag name="textPersonName" value="0x00000061" /> <flag name="textPostalAddress" value="0x00000071" /> <flag name="textPassword" value="0x00000081" /> <flag name="textVisiblePassword" value="0x00000091" /> <flag name="textWebEditText" value="0x000000a1" /> <flag name="textFilter" value="0x000000b1" /> <flag name="textPhonetic" value="0x000000c1" /> <flag name="textWebEmailAddress" value="0x000000d1" /> <flag name="textWebPassword" value="0x000000e1" /> <flag name="number" value="0x00000002" /> <flag name="numberSigned" value="0x00001002" /> <flag name="numberDecimal" value="0x00002002" /> <flag name="numberPassword" value="0x00000012" /> <flag name="phone" value="0x00000003" /> <flag name="datetime" value="0x00000004" /> <flag name="date" value="0x00000014" /> <flag name="time" value="0x00000024" /> </attr> <!-- set clear button padding --> <attr name="clearButtonPadding" format="dimension" /> <!-- set clear button height --> <attr name="clearButtonHeight" format="dimension" /> <!-- set clear button width --> <attr name="clearButtonWidth" format="dimension" /> <!-- set editText height --> <attr name="editTextHeight" format="dimension" /> <!-- set editText password --> <attr name="password" format="boolean" /> <!-- set editText singleLine --> <attr name="singleLine" format="boolean" /> <!-- set clearButton function works or not --> <attr name="enableClearFunction" format="boolean" /> <!-- set editText maxLength --> <attr name="maxLength" format="integer" min="0" /> <!-- set clearButton Drawable --> <attr name="drawableClearButton" format="reference" /> </declare-styleable> </resources>
如上图的布局为:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.yiduoyun.cloudschool" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#f0f0f0" android:orientation="vertical" android:padding="15dp" > <com.yiduoyun.cloudschool.view.CommonEditText android:id="@+id/input_new_phonenumber" android:layout_width="fill_parent" android:layout_height="50dp" android:background="@drawable/setting_input_shape" android:maxLength="20" android:paddingLeft="15dp" android:paddingRight="15dp" app:clearButtonHeight="40dp" app:clearButtonPadding="10dp" app:clearButtonWidth="40dp" app:hint="@string/input_new_phone" app:inputType="phone" app:singleLine="true" app:textColor="#000000" app:textColorHint="#707070" app:textSize="14sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:orientation="horizontal" > <TextView android:id="@+id/send_authcode" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:background="#B9E5F0" android:gravity="center" android:text="@string/send_authcode" android:textColor="#01A9CD" /> <com.yiduoyun.cloudschool.view.CommonEditText android:id="@+id/input_authcode" android:layout_width="0dp" android:layout_height="40dp" android:layout_marginLeft="15dp" android:layout_weight="1" android:background="@drawable/setting_input_shape" android:paddingLeft="12dp" android:paddingRight="12dp" app:clearButtonHeight="40dp" app:clearButtonPadding="10dp" app:clearButtonWidth="40dp" app:hint="@string/input_authcode" app:inputType="number" app:singleLine="true" app:textColor="#000000" app:textColorHint="#707070" app:textSize="14sp" /> </LinearLayout> </LinearLayout>
5 附加一个输入框的shape文件setting_input_shape.xml:
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 实心 --> <solid android:color="#ffffff"/> <!-- 描边 --> <stroke android:width="1dp" android:color="#E2E2E2" /> </shape>
控件就可以使用了.