带删除按钮的EditText
在使用输入框的时候,常常需要在输入框后带有一键清除输入内容的按钮。采用自定义View的方式是复用性较高的方法。另一方面也可以采用控件“控件+监听”的较为简单的方法来实现。
布局文件:
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:text="账号:"android:textColor="#000000"android:gravity="center"android:textSize="16sp"/><EditTextandroid: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"/><TextViewandroid: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);//清除按钮,使用TextViewtvCloseUser.setVisibility(View.INVISIBLE);mEtUserName=(EditText)findViewById(R.id.etUser);//文本框//监听文本变化mEtUserName.addTextChangedListener(newTextWatcher(){@OverridepublicvoidonTextChanged(CharSequences,intstart,intbefore,intcount){if(s.length()>0){tvCloseUser.setVisibility(View.VISIBLE);}else{tvCloseUser.setVisibility(View.GONE);}}});//点击清除文本tvCloseUser.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){mEtUserName.setText("");}});//监听焦点变化,没有焦点则清除按钮不可见mEtUserName.setOnFocusChangeListener(newView.OnFocusChangeListener(){@OverridepublicvoidonFocusChange(Viewv,booleanhasFocus){if(hasFocus&&mEtUserName.getText().length()>0){tvCloseUser.setVisibility(View.VISIBLE);}else{tvCloseUser.setVisibility(View.GONE);}}});
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。