簡體   English   中英

如何動態地將可繪制對象添加到TextView

[英]How to dynamically add drawables to a TextView

我有一個listview顯示一個textviews列表。 我用一個函數格式化所說的文本視圖

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);        
   }

現在這都是偽的,但它可以工作。 我已經實現了。 但是,我現在的問題是以這種方式編寫它,這樣我就不必為了格式化文本視圖而進行一百萬次if-else調用。

誰能建議一種方法,讓我以更短/更優雅的方式做出這種邏輯? 任何幫助,評論,建議將不勝感激。

謝謝!

給您的繪圖對象匹配的文本名稱,例如蘋果的A.png。

然后,使用以下代碼從名稱中獲取其ID

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

簡單地做,

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

希望這可以幫助。 (我也喜歡@ 0xDEADC0DE的答案。

您如何使用地圖:

這是一個您可能會發現有用的線程

這是一個JavaScript線程,但我敢肯定您會對其加以利用-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM