我最近將Android Design庫從24.2.1升級到25.0.0。 之後,EditText中的「drawableX」功能不起作用。無法在TextTextLayout中的EditText中使用drawable
編輯01.11: 我瞭解到,如果您使用android:drawableStart而不是android:drawableLeft,則在xml中設置drawable將起作用。但編程設置設置drawables不起作用。我用它來創建一個「清除」按鈕來清空EditText。但是現在這個功能已經被打破了我會很感激任何解決方法或知識,如果這是從Google有意或錯誤!
我對現在的工作之前,但不清零編輯文本代碼:
public class ClearableErrorTextInputEditText extends ErrorTextInputEditText implements View.OnFocusChangeListener, View.OnTouchListener, TextWatcher {
private Drawable resIcon;
private OnFocusChangeListener childFocusListener;
public ClearableErrorTextInputEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup();
}
public ClearableErrorTextInputEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public ClearableErrorTextInputEditText(Context context) {
super(context);
setup();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (getCompoundDrawables()[2] != null) {
final boolean tappedClose = event.getX() > (getWidth() - getPaddingRight() - resIcon.getIntrinsicWidth());
if (tappedClose) {
setText("");
return false; // true will fail on emulator running 2.1 and physical keyboard/scroll wheel
}
}
}
return false;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener l) {
childFocusListener = l;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
setClearIconVisible(hasFocus && getText().length() > 0);
if (childFocusListener!=null){
childFocusListener.onFocusChange(v, hasFocus);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count){
super.onTextChanged(s, start, before, count);
setClearIconVisible(isFocused() && s.length() > 0);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {} // not interesting
@Override
public void afterTextChanged(Editable s) {} // // not interesting
private void setup() {
if(isInEditMode()){
return;
}
resIcon = getResources().getDrawable(R.drawable.ic_clear, null);
resIcon.setBounds(0, 0, resIcon.getIntrinsicWidth(), resIcon.getIntrinsicHeight());
setClearIconVisible(false);
super.setOnTouchListener(this);
super.setOnFocusChangeListener(this);
addTextChangedListener(this);
}
private void setClearIconVisible(final boolean visible){
final Drawable icon = visible ? resIcon : null;
setCompoundDrawables(getCompoundDrawables()[0],
getCompoundDrawables()[1], icon, getCompoundDrawables()[3]);
}
在xml中添加drawable時,此工作起作用! – Gober
是的,這很奇怪,但drawableLeft不應該依賴於drawableStart,可能是一個bug。 –
但我真正的問題是,我想以編程方式進行,因爲我顯示並隱藏清除圖標,如果有文本或沒有。我使用setCompoundDrawables(),並且它沒有顯示任何內容(之前做過) – Gober