【发布时间】:2018-03-24 21:34:37
【问题描述】:
我有一个用于搜索目的的 EditText 字段。现在我的要求是在文本框中存在任何文本时在 drawableRight 上设置清除图标,并在没有文本时隐藏 drawableRight 图标。在这个 EditText 中,我实现了两个 Listener:
-
setOnTouchListener
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_ticket); txtBookingCode.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); txtBookingCode.setOnTouchListener(this); } public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (txtBookingCode.getRight() - txtBookingCode.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { txtBookingCode.setText(""); return true; } } return false; } -
addTextChangedListener
txtBookingCode.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { if(!s.toString().isEmpty()) txtBookingCode.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_clear_white, 0); else txtBookingCode.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } });
现在,这里第一次没有显示清晰的图标,因为文本框中没有任何文本。现在,如果我在文本框内触摸以键入搜索数据,则应用程序会引发错误并关闭应用程序。如果我不隐藏清除图标然后触摸文本框,则不会发生错误。
我得出的最终结论是,如果有清除图标,则没有错误,否则在触摸文本框(内部任何地方)时会出错。
我也在下面放了xml代码。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/dp_30"
android:theme="@style/SettingTextLabel"
app:hintTextAppearance="@style/SettingTextLabel">
<EditText
android:id="@+id/txtBookingCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@drawable/ic_clear_white"
android:textColor="@color/colorWhite"
android:textSize="@dimen/txt_20sp"
android:hint="@string/hint_Search" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
更新:
我收到日志错误:
W/InputDispatcher: channel 'f2c62c8 com.posorbis.ticketscan/com.posorbis.ticketscan.SearchTicketActivity (server)' ~ 消费者关闭输入通道或发生错误。事件=0x9
【问题讨论】:
-
你可以通过使用文本观察器来做到这一点。
-
首先以简单的方式实现它。并排放置一个edittext和一个imagebutton,这样如果没有image按钮,edittext就会占据所有空间。
-
然后在 onTextChanged 如果文本只是空字符串隐藏图像按钮,如果不显示图像按钮
-
@Shubham Agarwal Bhewanewala,我可以按照你说的做,但我想实现自己提供的任何 android。
-
能否提供错误日志?
标签: java android android-edittext android-image