2013-07-17 33 views
1

好的人,我在这里认真地坚持下去。深夜的东西,当你已经尝试了所有的东西...更改Android复合TextView中的图像 - 无法正常工作

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

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

tv是TextView变量。这工作正常。不过,后来我想更换新绘制的图像,我试图再次拨打setCompoundDrawables:

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

我还试图获得可绘为TextView的阵列和更换左之一,如下所示:

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

代码在调试模式下运行正常。没有例外发生。 UI线程中执行的所有UI处理。图像似乎没问题,等等,但显示不变。我需要以某种方式刷新显示吗?

顺便说一句,如果有问题,TextView会添加到垂直LinearLayout中。我很确定我错过了一些明显的东西,但我看不到它。提前谢谢了。

(是的,我知道我可以用的ImageView和TextView的香草代替我的设计,但是性能方面的原因我宁愿坚持一个复合的TextView如果可能的话)

+0

您可以使用带有自定义适配器的列表视图,并使用延迟加载来显示图像。这样一来,从你这边来看就不那么复杂了。 –

+0

第二种方法我不希望工作正常,至少没有'invalidate()'和'requestLayout()'。我期望通过观察'TextView'源代码来工作的第一种方法(我从未尝试过自己改变这些...)。你可以尝试用四个'null'值调用'setCompoundDrawables()',然后用新图像调用'setCompoundDrawables()'。原则上,这四个'''''会使你回到原来的状态,在这种情况下,新的'setCompoundDrawables()'应该和原来的一样。 – CommonsWare

+0

非常感谢你们。我不熟悉延迟加载,所以会看起来。此外,自定义适配器听起来值得一试。 –

回答

2

确定。我得到了这个工作,但Android似乎对它的工作方式非常挑剔。如果有人帮助其他人,我会发布答案。

这是有效的代码。没有什么特别的,直到你阅读下面的评论,显示其他方法无效。

// 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 

希望这可以帮助别人。干杯,汤姆

相关问题