【问题标题】:Calculate image size when using setCompoundDrawables for EditText对 EditText 使用 setCompoundDrawables 时计算图像大小
【发布时间】:2011-11-20 00:43:40
【问题描述】:

当我添加如下图标时:

etComment = (EditText) findViewById(R.id.et_comment);
Drawable img = getResources().getDrawable( R.drawable.warning );
etComment.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );

图标调整 EditText 的大小。如何计算 img 大小并将其放入 EditText 而不调整 EditText 大小?

谢谢!


FunkTheMonk
使用 setCompounDrawables() 而不是 setCompoundDrawablesWithIntrinsicBounds() - 您必须手动设置可绘制对象的边界。

我不明白如何手动计算边界。我有 EditText 的高度和宽度:

etComment = (EditText) findViewById(R.id.et_comment);
Drawable img = getResources().getDrawable( R.drawable.warning );
int size = etComment.getHeight();
img.setBounds(0, 0, size, size);
etComment.setCompoundDrawables( img, null, null, null );

但我在不同的屏幕尺寸下有不同的结果。如何计算图标的正确大小和填充?你能帮帮我吗?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    我认为你可以为不同的屏幕使用不同大小的图片,并使用getMinimumWidth来设置Bounds。但我之前没有尝试过,可能不适合.9补丁。

    当你使用 setCompoundDrawables 时,你需要这样的代码:

    Drawable img;
    Resources res = getResources();
    img = res.getDrawable(R.drawable.btn_img);
    //You need to setBounds before setCompoundDrawables , or it couldn't display
    img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
    btn.setCompoundDrawables(img_off, null, null, null); 
    

    【讨论】:

    • 在按钮中调整图像大小时效果很好,非常感谢
    • 最后一行的 img_off 是什么?
    【解决方案2】:

    我在this 帖子中找到了解决方案。

    Drawable dr = this.getResources().getDrawable(R.drawable.warning);
    Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
    Drawable d = new BitmapDrawable(this.getResources(), Bitmap.createScaledBitmap(bitmap, 35, 35, true));
    
    txtValue.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null);
    

    HTH, 米尔顿

    【讨论】:

    • 'java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable' 我收到这个错误,你能告诉我哪里错了吗?
    • @sumitmehra 您应该提出一个单独的问题以获得答案。您收到此错误是因为您将 SVG 加载为可绘制位图。
    【解决方案3】:

    使用 setCompoundDrawables() 而不是 setCompoundDrawablesWithIntrinsicBounds() - 您必须手动设置可绘制对象的边界。

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      相关资源
      最近更新 更多