I have a listview that displays a list of 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.

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.

Then, use the below to get its id from name

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. :))

其他提示

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-

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top