[英]OnTouchListener is not working in EditText when no drawable is present in android application?
我有一個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:通道'f2c62c8 com.posorbis.ticketscan / com.posorbis.ticketscan.SearchTicketActivity(服務器)'〜使用者關閉輸入通道或發生錯誤。 事件= 0x9
一個簡單的textwatcher很好。 在afterTextChanged
方法中執行代碼。 如果將某些Log方法放在textwatcher覆蓋方法中,您會發現它們在文本輸入期間被調用很多,因此它們可能會相互干擾。
除了afterTextChanged之外,將所有方法保持空白,並查看對圖標有什么影響。 然后從那里去。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.