【问题标题】:Changing the image in an Android compound TextView - not working更改 Android 复合 TextView 中的图像 - 不起作用
【发布时间】:2013-07-17 11:47:46
【问题描述】:

好吧,伙计们,我真的要疯了。当你尝试了所有的东西时,深夜的东西......

我有一个复合 TextView,左侧有一个图像。图像(只是说“正在加载”的小图片)设置为:

Drawable img = getBaseContext().getResources().getDrawable( R.drawable.loading );
img.setBounds( 0, 0, 120, 120 );
tv.setCompoundDrawables( img, null, null, null );

tv 是 TextView 变量。这很好用。但是,稍后我想用新的drawable替换图像,我尝试再次调用setCompoundDrawables:

tv.setCompoundDrawables( new_img, null, null, null );

我还尝试获取 TextView 的可绘制数组并替换左侧的数组,如下所示:

Drawable[] drw = tv.getCompoundDrawables();
drw[0] = new_img;

代码在调试模式下运行正常。没有异常发生。在 UI 线程中执行的所有 UI 处理。图像似乎还可以,等等,但显示没有改变。我是否必须以某种方式刷新显示?

顺便说一句,如果重要的话,TextViews 会被添加到一个垂直的 LinearLayout 中。我很确定我在这里遗漏了一些明显的东西,但我看不到它。非常感谢。

(是的,我知道我可以用 ImageView 和 vanilla TextView 替换我的设计,但是出于性能原因,如果可能的话,我更愿意坚持使用 Compound TextView)

【问题讨论】:

  • 您可以使用带有自定义适配器的列表视图并使用延迟加载来显示图像。这样一来,从您的角度来看,它就不那么复杂了。
  • 第二种方法我不希望正常工作,至少没有invalidate()requestLayout()。通过观察TextView 源代码(我从未尝试过自己更改这些...),这是我期望的第一种方法。您可以尝试使用四个 null 值调用 setCompoundDrawables(),然后使用新图像调用 setCompoundDrawables()。原则上,四个nulls 会让你回到原来的状态,在这种情况下,新的setCompoundDrawables() 应该和你原来的一样工作。
  • 非常感谢大家。我不熟悉延迟加载,所以会查一下。此外,自定义适配器听起来值得一试。

标签: android textview android-drawable


【解决方案1】:

setCompoundDrawables() 无法解码可绘制对象的边界框。
相反,使用TextView::setCompoundDrawablesWithIntrinsicBounds() 为可绘制对象使用隐式边界。这将确保更好地处理不同的屏幕密度。

【讨论】:

    【解决方案2】:

    好的。我得到了这个工作,但Android似乎对它的工作方式非常挑剔。我发布答案以防它帮助其他人。

    这是有效的代码。没什么特别的,直到您阅读下面的 cmets 显示其他方法不起作用。

    // resize the images. these methods seem to be very particular about how the bounds are set
    img.setBounds(new Rect(0, 0, 120, 120));    // it likes this
    tvp.setCompoundDrawables( img, null, null, null );  // this works for sure when combined with setBounds(Rect)
    
    // what didn't work... (would have to more experimenting with what works and what doesn't)
    //img.setBounds( 0, 0, 240, 240 ); // it didn't like this!
    
    //Drawable[] drw = tvp.getCompoundDrawables();
    //drw[0] = img;     // it didn't like this technique of assigning a new image
    
    //tvp.setCompoundDrawablesRelativeWithIntrinsicBounds(img, null, null, null);   // no good, as it uses original (intrinsic) size of the image
    //tvp.setCompoundDrawablesRelative(img, null, null, null);  // doesn't like this - nothing bad happens; it just doesn't change the image
    

    希望这对某人有所帮助。干杯,汤姆

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2016-08-01
      • 2014-07-19
      • 2021-10-22
      • 1970-01-01
      相关资源
      最近更新 更多