帮我动态更改TextView颜色?

时间:2011-06-30 16:21:37

标签: java android

我想知道如何动态更改TextView的颜色。似乎有一些东西在那里,但现在我正在寻找...我在这里做的是迭代一个数组,如果它的“+”我希望文本是绿色,如果它的“ - ”我想要的文本是红色的,问题是我在ct.setTextColor(.....)得到空指针错误任何人都知道为什么?

这是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>

和代码snippit

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

1 个答案:

答案 0 :(得分:1)

如果上面的代码片段是您从onCreate()方法中复制并粘贴的代码片段,那么我看到为什么它会给您一个空指针错误的主要问题是因为您没有将当前活动的视图设置为包含所有内容的XML布局。换句话说,findViewById()不知道您在哪里找到您所指的ID。尝试将此添加到onCreate()的第一行,或在调用findViewById()之前的任何位置:

setContentView(R.id.yourLinearLayout);

相关问题