自带clear图标效果的搜索栏,自带clear图标,闲的蛋疼,就随手写了个d
分享于 点击 1495 次 点评:163
自带clear图标效果的搜索栏,自带clear图标,闲的蛋疼,就随手写了个d
闲的蛋疼,就随手写了个dota的android应用。这个component就是用在查询那边的
android平台应该都能用吧,我自己是在2.1环境下写的。
package studio.five.common.component;import android.content.Context;import android.graphics.drawable.Drawable;import android.text.Editable;import android.text.InputType;import android.text.TextUtils;import android.text.TextWatcher;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.AutoCompleteTextView;/** * @author jlcoa * @date 2012-7-10 * @version $Revision$ */public class SearchTextView extends AutoCompleteTextView { private Drawable[] compoundDrawables; private Drawable clearDrawable; private int clearDrawableWidth; /** * @param context * @param attrs */ public SearchTextView(Context context, AttributeSet attrs) { super(context, attrs); compoundDrawables = this.getCompoundDrawables(); clearDrawable = compoundDrawables[2]; clearDrawableWidth = clearDrawable.getBounds().width() + this.getPaddingRight() + this.getCompoundDrawablePadding(); this.displayClearDrawable(false); this.addTextChangedListener(new DisplayClearDrawableListener(this)); this.setOnTouchListener(new ClickClearDrawableListener(this)); } private void displayClearDrawable(boolean show) { this.setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], show ? compoundDrawables[2] : null, compoundDrawables[3]); } public static class DisplayClearDrawableListener implements TextWatcher { private final SearchTextView txt; DisplayClearDrawableListener(final SearchTextView txt) { this.txt = txt; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if (txt.getText().length() > 0) { txt.displayClearDrawable(true); } else { txt.displayClearDrawable(false); } } } public static class ClickClearDrawableListener implements OnTouchListener { private final SearchTextView txt; ClickClearDrawableListener(final SearchTextView txt) { this.txt = txt; } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: int curX = (int) event.getX(); if (curX > v.getWidth() - txt.clearDrawableWidth && !TextUtils.isEmpty(txt.getText())) { txt.setText(""); int cacheInputType = txt.getInputType();// backup the input type txt.setInputType(InputType.TYPE_NULL);// disable soft input txt.onTouchEvent(event);// call native handler txt.setInputType(cacheInputType);// restore input type // InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); // txt.requestFocus(); // imm.showSoftInput(txt, 0); return false; // let txt focus still } break; } return false; } }}//该片段来自于http://byrx.net
用户点评