2011-06-30 51 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