功能:编辑框中带有清除按钮,输入文本按钮显示,没有文本按钮隐藏,点击按钮可以清除所有的文本
页面布局
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/title_marginLeft"
android:layout_marginLeft="@dimen/title_marginLeft"
android:layout_marginRight="@dimen/title_marginLeft"
android:orientation="vertical" >
<EditText
android:id="@+id/jianyi_qq_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_information_d"
android:lines="2"
android:maxLength="11"
android:numeric="integer"
android:paddingLeft="@dimen/title_marginLeft" />
<ImageView
android:id="@+id/fankui_img_cleanPhoneNum"
android:layout_width="@dimen/image_margin"
android:layout_height="@dimen/image_margin"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_margin="@dimen/title_marginLeft"
android:background="@drawable/qingchu"
android:visibility="gone" />
</RelativeLayout>
代码监听事件
/**定义*/
private EditText phoneNumber;
/**找到编辑框的位置*/
phoneNumber = (EditText) findViewById(R.id.jianyi_qq_et);
/* 监听 编辑框中的文本改变事件 */
phoneNumber.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
/* ++ 文本每次改变就会跑这个方法 ++ */
delPhoneNumber();
/**隐藏密码 */
phoneNumber.setTransformationMethod(PasswordTransformationMethod
.getInstance());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
delPhoneNumber();
}
@Override
public void afterTextChanged(Editable s) {
delPhoneNumber();
}
});
/**隐藏显示清除按钮的方法,注意是控件名的长度不是获得控件文本的长度*/
private void delPhoneNumber() {
if (phoneNumber.length() > 0) {
fankui_img_cleanPhoneNum.setVisibility(View.VISIBLE);
} else {
fankui_img_cleanPhoneNum.setVisibility(View.INVISIBLE);
}
}
在介绍下EditText获取失去焦点的时候实现的一些操作
EditText searchView = (EditText) findViewById(R.id.search_text);
searchView.setOnFocusChangeListener(new android.view.View.
OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// 此处为得到焦点时的处理内容
} else {
// 此处为失去焦点时的处理内容
}
}
});