如何以编程方式隐藏可绘制对象权利



我正在为EditText设置可绘制对象,如下所示,

editText.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_clear_black_24dp), null);

我正在为 xml 中的编辑文本设置左侧可绘制对象。我想将其可见性设置为可见或隐藏。我如何以编程方式执行此操作。

我有用于搜索的编辑文本。开始打字时,我正在以编程方式设置清晰的图标。

清除图标将清除编辑文本中的文本。单击没有文本的清除图标时,我想关闭键盘并进行清晰图标隐藏。 下面是我的代码,

editText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText.setCursorVisible(true);
editText.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_clear_black_24dp), null);
}
});
editText.setOnTouchListener(new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
if(editText.getCompoundDrawables()[2]!=null){
if(event.getX() >= (editText.getRight()- editText.getLeft() - editText.getCompoundDrawables()[2].getBounds().width())) {
if(!editText.getText().toString().equals("")) {
editText.setText("");
}
else {
// getWindow().setSoftInputMode(
//       WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
closeKeyboard();
editText.setCursorVisible(false);
}
}
}
}
return false;
}
});

我想以编程方式隐藏它。

只需在setCompoundDrawablesWithIntrinsicBounds()方法中传递null即可从editText隐藏 Drawable

示例代码

editText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);

请按如下方式更改您的onTouchListener。与其寻求捕获ACTION_UP不如选择ACTION_DOWN因为它将在return trueonTouch中首先调用,因为现在我们不需要在关闭键盘时onClick

editText.setOnTouchListener(new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
if(editText.getCompoundDrawables()[2]!=null){
if(event.getX() >= (editText.getRight()- editText.getLeft() - editText.getCompoundDrawables()[2].getBounds().width())) {
if(!editText.getText().toString().equals("")) {
editText.setText("");
}
else {
// getWindow().setSoftInputMode(
//       WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
editText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
closeKeyboard();
editText.setCursorVisible(false);
return true;
}
}
}
}
return false;
}
});

尝试

editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

为空右可绘制对象

editText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);

这里第三个参数是右绘制的。

或者您可以使用

editText.setCompoundDrawables(null,null, null, null);

海尔

设置复合可绘制对象(左、上、右、下(

最新更新