Android 編程中文字框中搜尋和清空效果實現

來源:互聯網
上載者:User

   本文

  一、實現效果

  二、實現代碼

  監聽輸入

  /**

  * 動態搜尋

  */

  private TextWatcher tbxSearch_TextChanged = new TextWatcher() {

  //緩衝上一次文字框內是否為空白

  private boolean isnull = true;

  @Override

  public void afterTextChanged(Editable s) {

  if (TextUtils.isEmpty(s)) {

  if (!isnull) {

  mSearchView.setCompoundDrawablesWithIntrinsicBounds(null,

  null, mIconSearchDefault, null);

  isnull = true;

  }

  } else {

  if (isnull) {

  mSearchView.setCompoundDrawablesWithIntrinsicBounds(null,

  null, mIconSearchClear, null);

  isnull = false;

  }

  }

  }

  @Override

  public void beforeTextChanged(CharSequence s, int start, int count,

  int after) {

  }

  /**

  * 隨著文字框內容改變動態改變列表內容

  */

  @Override

  public void onTextChanged(CharSequence s, int start, int before,

  int count) {

  }

  };

  觸摸事件

  private OnTouchListener txtSearch_OnTouch = new OnTouchListener() {

  @Override

  public boolean onTouch(View v, MotionEvent event) {

  switch (event.getAction()) {

  case MotionEvent.ACTION_UP:

  int curX = (int) event.getX();

  if (curX > v.getWidth() - 38

  && !TextUtils.isEmpty(mSearchView.getText())) {

  mSearchView.setText("");

  int cacheInputType = mSearchView.getInputType();// backup the input type

  mSearchView.setInputType(InputType.TYPE_NULL);// disable soft input

  mSearchView.onTouchEvent(event);// call native handler

  mSearchView.setInputType(cacheInputType);// restore input type

  return true;// consume touch even

  }

  break;

  }

  return false;

  }

  };

  綁定事件

  private Drawable mIconSearchDefault; // 搜尋文字框預設表徵圖

  private Drawable mIconSearchClear; // 搜尋文字框清除常值內容表徵圖

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main)

  final Resources res = getResources();

  mIconSearchDefault = res.getDrawable(R.drawable.txt_search_default);

  mIconSearchClear = res.getDrawable(R.drawable.txt_search_clear);

  mSearchView = (EditText) findViewById(R.id.txtSearch);

  mSearchView.addTextChangedListener(tbxSearch_TextChanged);

  mSearchView.setOnTouchListener(txtSearch_OnTouch);

  }

  代碼說明:

  1. 為輸入框綁定觸摸事件(類比點擊事件捕捉)。通過監聽點擊地區判斷是否點擊清空圖片,如果在該地區並且文字框不為空白,則清空文字框。

  2. 為輸入框綁定文本改變事件監聽,根據內容改變動態設定表徵圖顯示。

  3. 維持清空操作後軟鍵盤狀態。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.