【问题标题】:How can I change default ImageView color based on EditText length() test?如何根据 EditText length() 测试更改默认 ImageView 颜色?
【发布时间】:2015-10-29 03:04:15
【问题描述】:

我有一个默认为白色的图标,使用 ImageView 和 drawable。我希望按下时颜色变为黑色。当 EditText 行获得文本时(因为用户在行上输入了一些数据),我希望图标变为灰色。目前,当长度测试>0时,图标变为黑色,按下图标时没有任何变化(因为颜色已经是黑色)。然后当长度测试为 == 0 时,当它应该恢复为默认颜色白色时,颜色保持黑色。我在这里错过了什么?

活动文件:

protected void OnCreate...
fEditText = (EditText) findViewById(R.id.FEditText); 
@Override
        public void afterTextChanged(Editable s) {
            fTextInputLayout.setHint("Due Date");
            if (fEditText.getText().length() > 0) {
               imgcan = (ImageView) findViewById(R.id.imageView1);
               imgcan.setImageResource(R.drawable.ic_delete_54per24);
               <!-- "ic_delete_54per24 is the the gray icon drawable -->
            }
        }

Xml 布局文件:

...
<ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:onClick="onClickClearDate"
        android:clickable="true"
        android:src="@drawable/trash_can"  />

trash_can 可绘制文件:

...
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
    android:drawable="@drawable/ic_delete_black_24dp" />
    <!-- black color when pressed -->
<item android:drawable="@drawable/ic_delete_white_24dp" />
    <!-- white color when normal (default) -->

【问题讨论】:

    标签: android android-edittext android-imageview android-drawable


    【解决方案1】:

    也许你错过了在文本为空时重置彩色图像,像这样:

     if (fEditText.getText().length() > 0) {
           imgcan = (ImageView) findViewById(R.id.imageView1);
           imgcan.setImageResource(R.drawable.ic_delete_54per24);
      }else{ //add this
          imgcan = (ImageView) findViewById(R.id.imageView1);
          imgcan.setImageResource(R.drawabale.ic_delete_white_24dp);
      }
    

    【讨论】:

    • 好的,很好。当 EditText 为空时,这会使图标恢复为默认的白色。现在我只需要弄清楚为什么没有出现灰色图标。有什么想法吗?
    • afterTextChanged 将在您停止编辑一段时间后被调用。要检查它为什么不起作用,请添加登录 afterTextChanged 和 if (fEditText.getText().length() > 0)' s 条件为真。
    • 我将灰色更改为更浅的版本,并确认一切正常。谢谢,回答被接受并赞成。干杯。
    【解决方案2】:

    试试 Textwatcher 吗?

    editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
    }
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(TextUtils.isEmpty(s)){
            imageView.setImageResource(R.drawable.ic_delete_54per24);
        }
    
    }
    
    @Override
    public void afterTextChanged(Editable s) {
    
    }
    });
    

    【讨论】:

    • 是的,我在上面的 Activity 文件中显示:“public void afterTextChanged(Editable s)...”。
    猜你喜欢
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2014-08-31
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多