2012-05-08 58 views
2

已經淘到這個網站的任何答案,沒有真正簡單的解決方案,我找到了這個。我正在創建一個Android應用程序,它使用sqlite數據庫通過輸入的顏色名稱查找十六進制值。我動態創建一個TextView,設置其文本和文本顏色,然後將其添加到ArrayList,然後ArrayList正在添加到ListView中。該文本顯示在ListView中,但其顏色屬性未設置。我真的很想找到一種方法來爲每個listview項目設置文本顏色。這裏是我的代碼至今:在一個listview項目中設置文本視圖的文本顏色? (Android)

類變量:

private ListView lsvHexList; 

private ArrayList<String> hexList; 
private ArrayAdapter adp; 

在的onCreate():

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.color2hex); 

    lsvHexList = (ListView) findViewById(R.id.lsvHexList); 

    hexList = new ArrayList<String>(); 

在我的按鈕處理程序:

public void btnGetHexValueHandler(View view) { 

    // Open a connection to the database 
    db.openDatabase(); 

    // Setup a string for the color name 
    String colorNameText = editTextColorName.getText().toString(); 

    // Get all records 
    Cursor c = db.getAllColors(); 

    c.moveToFirst(); // move to the first position of the results 

    // Cursor 'c' now contains all the hex values 
    while(c.isAfterLast() == false) { 

     // Check database if color name matches any records 
     if(c.getString(1).contains(colorNameText)) { 

      // Convert hex value to string 
      String hexValue = c.getString(0); 
      String colorName = c.getString(1); 

      // Create a new textview for the hex value 
      TextView tv = new TextView(this); 
      tv.setId((int) System.currentTimeMillis()); 
      tv.setText(hexValue + " - " + colorName); 
      tv.setTextColor(Color.parseColor(hexValue)); 

      hexList.add((String) tv.getText()); 

     } // end if 

     // Move to the next result 
     c.moveToNext(); 

    } // End while 

    adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexList); 
    lsvHexList.setAdapter(adp); 


    db.close(); // close the connection 
    } 

回答

3

您沒有添加創建TextView到列表中,您只需將String添加到列表中,因此無論您在TextVi上調用什麼方法EW:

 if(c.getString(1).contains(colorNameText)) { 
     // ... 
     TextView tv = new TextView(this); 
     tv.setId((int) System.currentTimeMillis()); 
     tv.setText(hexValue + " - " + colorName); 
     tv.setTextColor(Color.parseColor(hexValue)); 

     hexList.add((String) tv.getText()); // apend only the text to the list 
     // !!!!!!!!!!!!!! lost the TextView !!!!!!!!!!!!!!!! 
    } 

你需要做的是將顏色存儲在另一個數組,並創建實際列表視圖時,根據列表中的相應值設置每個TextView的顏色。

要做到這一點,您需要擴展ArrayAdapter並在其中添加TextView顏色的邏輯。

+0

聽起來不錯。這看起來代碼明智嗎?這裏有一個新手程序員。 = P –

+0

我現在沒有ListAdapter示例,但請參閱下面的鏈接來擴展BaseAdapter,這個想法幾乎相同:https://github.com/BinyaminSharet/Icelandic-Memory-Game/blob/master /src/com/icmem/game/BoardGridAdapter.java – MByD

+0

不完全有幫助。還有誰? –

相關問題