Help me change TextView color dynamically?
I would like to know how to change the color of a TextView dynamically. It seems there is some stuff out there but now quite what I'm looking for.. what i'm doing here is iterating an array and if its "+" i want the text to be greem if its "-" i want the text to be red, the problem is that i'm getting null pointer error at ct.setTextColor(.....) anyone have any idea why?
here is the 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开发者_StackOverflow中文版
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>
and the code 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);
If this code snippet above is what you copied-and-pasted out of your onCreate() method, then the main problem I see why it's giving you a null pointer error is because you haven't set the current activity's view to the XML layout with all the stuff in it. In other words, findViewById() doesn't know where you find those ID's you're referring to. Try adding this to the first line of your onCreate(), or anywhere before you call findViewById():
setContentView(R.id.yourLinearLayout);
精彩评论