国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

簡要概述Android文本框搜索和清空的代碼實現(xiàn)

2020-02-21 17:35:25
字體:
來源:轉載
供稿:網(wǎng)友

在編程的工作過程中,可能會遇到這樣的問題,單擊空圖標可以清空文本框中的文本,下文是簡要概述Android文本框搜索和清空的代碼實現(xiàn),感興趣的小伙伴們可以參考一下。

簡要概述Android文本框搜索和清空的代碼實現(xiàn)
一、實現(xiàn)效果
  
  
二、實現(xiàn)代碼
綁定事件

復制代碼 代碼如下:

private Drawable mIconSearchDefault; // 搜索文本框默認圖標
private Drawable mIconSearchClear; // 搜索文本框清除文本內(nèi)容圖標
@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);
}


觸摸事件

復制代碼 代碼如下:


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;
}
};

復制代碼 代碼如下:


//監(jiān)聽輸入
/**
* 動態(tài)搜索
*/
private TextWatcher tbxSearch_TextChanged = new TextWatcher() {
//緩存上一次文本框內(nèi)是否為空
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) {
}
/**
* 隨著文本框內(nèi)容改變動態(tài)改變列表內(nèi)容
*/
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};


代碼說明
1.為輸入框綁定觸摸事件(模擬點擊事件捕捉)。通過監(jiān)聽點擊區(qū)域判斷是否點擊清空圖片,如果在該區(qū)域并且文本框不為空,則清空文本框。
2.為輸入框綁定文本改變事件監(jiān)聽,根據(jù)內(nèi)容改變動態(tài)設置圖標顯示。
3.維持清空操作后軟鍵盤狀態(tài)。

以上是簡要概述Android文本框搜索和清空的代碼實現(xiàn),希望對大家的學習有一定的幫助!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 辽阳市| 报价| 禄劝| 芮城县| 铜梁县| 开平市| 田阳县| 沾化县| 霍山县| 彩票| 清流县| 龙胜| 北安市| 阜南县| 类乌齐县| 团风县| 海淀区| 江油市| 靖江市| 都昌县| 彩票| 黔东| 营口市| 萨嘎县| 汉阴县| 阳朔县| 永州市| 宝丰县| 绍兴县| 河间市| 贞丰县| 平泉县| 大同县| 湘阴县| 沙洋县| 巴林右旗| 曲松县| 皋兰县| 鞍山市| 崇信县| 喀什市|