简体   繁体   English

如何动态地将可绘制对象添加到TextView

[英]How to dynamically add drawables to a TextView

I have a listview that displays a list of textviews. 我有一个listview显示一个textviews列表。 I format the said textviews with a function tha goes something like 我用一个函数格式化所说的文本视图

private void myFunc(TextView tv){
   if(tv.getText.toString().contains("A")){
       tv.setDrawableLeft(R.id.apple);        
   }else if(tv.getText.toString().contains("A")){
       tv.setDrawableLeft(R.id.apple);        
   }else if(tv.getText.toString().contains("B")){
       tv.setDrawableLeft(R.id.ball);        
   }...
   else if(tv.getText.toString().contains("Z")){
       tv.setDrawableLeft(R.id.zebra);        
   }

now this is all pseudo, but it works. 现在这都是伪的,但它可以工作。 I have implemented it. 我已经实现了。 However, my problem now is being able to write it in such a way that I would NOT have to go through a million if-else calls just to be able to format my textviews. 但是,我现在的问题是以这种方式编写它,这样我就不必为了格式化文本视图而进行一百万次if-else调用。

Can anyone suggest a way in order for me to make this logic with a much shorter/more elegant way? 谁能建议一种方法,让我以更短/更优雅的方式做出这种逻辑? Any help, comment, suggestion would be greatly appreciated. 任何帮助,评论,建议将不胜感激。

Thank you! 谢谢!

Give your drawables the Names of the text you are matching like A.png for apple. 给您的绘图对象匹配的文本名称,例如苹果的A.png。

Then, use the below to get its id from name 然后,使用以下代码从名称中获取其ID

public int getID(String drawableName){
   Resources resources = context.getResources();
   final int resourceId = resources.getIdentifier(drawableName, "drawable", 
   context.getPackageName());
   return resources.getDrawable(resourceId);
}

and simply do, 简单地做,

tv.setDrawableLeft(getID(tv.getText.toString()));

Hope this helps. 希望这可以帮助。 (I like @0xDEADC0DE answers as well. :)) (我也喜欢@ 0xDEADC0DE的答案。

how about you use a map: 您如何使用地图:

Here's a thread that you might find useful 这是一个您可能会发现有用的线程

it's a javascript thread but i'm sure you'll make some use of it- 这是一个JavaScript线程,但我敢肯定您会对其加以利用-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM