2011-06-30 127 views
0

我想知道如何動態改變TextView的顏色。看起來有一些東西在那裏,但現在完全是我在找什麼..我在這裏做的是迭代一個數組,如果它的「+」我想要文本是格林如果它的「 - 」我想文本是紅色的,問題是我得到空指針錯誤在ct.setTextColor(.....)任何人都有任何想法爲什麼?幫我改變TextView的顏色動態?

這裏是XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="?android:attr/listPreferredItemHeight" 
    android:padding="6dip"> 
    <ImageView 
     android:id="@+id/icon" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:layout_marginRight="6dip" 
     android:src="@drawable/icon" /> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="0dip" 
     android:layout_weight="1" 
     android:layout_height="fill_parent"> 
     <TextView 
      android:id="@+id/tt" 
      android:layout_width="fill_parent" 
      android:layout_height="0dip" 
      android:layout_weight="1" 
      android:gravity="center_vertical" 
     /> 
     <TextView 
      android:layout_width="fill_parent" 
      android:layout_height="0dip" 
      android:layout_weight="1" 
      android:id="@+id/bt" 
      android:singleLine="true" 
      android:ellipsize="marquee" 
     /> 
    </LinearLayout> 
    <TextView 
     android:id="@+id/pm" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:layout_gravity="right" 
     android:text="-" 

     android:textSize="30sp" 
     android:textStyle="bold" 
     /> 
</LinearLayout> 

和代碼片段

int c = count; 
    ind = (count); 
    j=0; 
    TextView ct = (TextView)findViewById(R.id.pm); 
    funkAdapter = (new ArrayAdapter<String>(this, R.layout.rowneg, R.id.pm)); 
    String[] tmpAry= new String[count]; 
    for (int i = 0; i < ind; i = i+2){ 
     tmpAry[j] = dataAryArray[i]; 

     if (tmpAry[j].equals("-")){ 
     funkAdapter.add(tmpAry[j]); 
     ct.setTextColor(Color.RED); 
     }else{ 
      funkAdapter.add(tmpAry[j]); 
      ct.setTextColor(Color.GREEN); 

     } 
     j++; 
    } 
    setListAdapter(funkAdapter); 
+0

添加堆棧跟蹤你的異常PLZ, – Houcine

+0

的這看起來可笑..可是我怎麼獲得這個? logcat的? – tricknology

+0

您可以通過在您的Android SDK所在的工具文件夾中使用DDMS來獲取堆棧跟蹤。在插入手機的情況下啓動DDMS,然後單擊紅色(E)符號以查找錯誤。 – Brian

回答

1

如果超過這個代碼段是複製和粘貼的什麼你的onCreate()方法中,則主要問題我明白了爲什麼它給你一個空指針錯誤是因爲你沒有將當前活動的視圖設置爲包含所有東西的XML佈局。換句話說,findViewById()不知道你在哪裏找到你所指的那些ID。你調用findViewById()嘗試添加這對您的onCreate()的第一行,或之前的任何地方:

setContentView(R.id.yourLinearLayout);

+0

他說nullPointerException給ct.setTextColor()..如果他沒有指定的內容hie活動,nullpointerException將在'ct =(TextView)findViewById(...)' – Houcine

+0

不,這不是真的Houcine。如果您沒有正確初始化setContentView(),findViewById()將無法找到當前活動中引用的視圖時返回null。直到他試圖使用該視圖(即調用ct.setTextColor()),它纔會崩潰,因爲TextView實際上是null。 – Brian

+0

我知道,但程序signale異常在ct.setTextColor(),如果TextView爲空,我認爲這個異常將在findViewById()發出信號? – Houcine