在使用輸入框的時候,常常需要在輸入框后帶有一鍵清除輸入內容的按鈕。采用自定義View的方式是復用性較高的方法。另一方面也可以采用控件“控件+監聽”的較為簡單的方法來實現。
布局文件:
<LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:text="賬號:" android:textColor="#000000" android:gravity="center" android:textSize="16sp"/> <EditText android:id="@+id/etUser" tools:text="test3" android:layout_width="0dp" android:layout_height="match_parent" android:background="@null" android:maxLength="16" android:layout_weight="1"/> <TextView android:id="@+id/closeUser" android:layout_width="20dp" android:layout_height="20dp" android:gravity="center" android:background="@drawable/icon_delete" android:textColor="@color/gray"/> </LinearLayout>
主要代碼:
tvCloseUser = (TextView) findViewById(R.id.closeUser);//清除按鈕,使用TextView
tvCloseUser.setVisibility(View.INVISIBLE);
mEtUserName = (EditText) findViewById(R.id.etUser);//文本框
//監聽文本變化
mEtUserName.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0){
tvCloseUser.setVisibility(View.VISIBLE);
}else{
tvCloseUser.setVisibility(View.GONE);
}
}
});
//點擊清除文本
tvCloseUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mEtUserName.setText("");
}
});
//監聽焦點變化,沒有焦點則清除按鈕不可見
mEtUserName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus && mEtUserName.getText().length() > 0){
tvCloseUser.setVisibility(View.VISIBLE);
}else {
tvCloseUser.setVisibility(View.GONE);
}
}
});
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。