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

首頁 > 系統 > Android > 正文

Android文本框搜索和清空效果實現代碼及簡要概述

2020-04-11 12:31:45
字體:
來源:轉載
供稿:網友
前言
本文實現的效果:文本框輸入為空時顯示輸入的圖標;不為空時顯示清空的圖標,此時點擊清空圖標能清空文本框內輸入文字。

正文
一、實現效果
  
  
二、實現代碼
綁定事件
復制代碼 代碼如下:

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

觸摸事件
復制代碼 代碼如下:

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

代碼說明
1.為輸入框綁定觸摸事件(模擬點擊事件捕捉)。通過監聽點擊區域判斷是否點擊清空圖片,如果在該區域并且文本框不為空,則清空文本框。
2.為輸入框綁定文本改變事件監聽,根據內容改變動態設置圖標顯示。
3.維持清空操作后軟鍵盤狀態。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乌兰察布市| 大荔县| 定南县| 西安市| 嫩江县| 大连市| 师宗县| 辽源市| 迭部县| 大英县| 南华县| 龙胜| 渭源县| 承德市| 铜鼓县| 汉寿县| 慈利县| 阳原县| 石河子市| 穆棱市| 长子县| 天柱县| 新闻| 衡南县| 会昌县| 鄂温| 沙坪坝区| 信宜市| 荔浦县| 桂林市| 孟州市| 南岸区| 来安县| 潜山县| 霍城县| 成都市| 班戈县| 卓尼县| 奇台县| 丹凤县| 车险|