如何更改ListView中的文本颜色

时间:2012-06-16 06:17:07

标签: android listview colors custom-lists

我正在开发我的第一个Android应用程序,经过这里发布的许多答案之后,他们已经完善了我的理解,但似乎无法解决我的问题。

简单地说,我有一个ListView,我希望某些行中的文本与其他行不同。我试图通过将ListView.GetItemAtPosition转换为TextView并更改其文本颜色来实现此目的,但我得到了一个转换异常。

要么帮助我弄清楚代码中的错误,要么建议更好的方法,我们将非常感激!

public class MeetingManager extends Activity {

public ListView mAgenda;

//public Item agenda = new Item();
List<Item> agenda=new ArrayList<Item>();
ArrayAdapter<Item> adapter=null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.meeting);

    // Obtain handles to UI objects
    mAgenda = (ListView)findViewById(R.id.lstAgenda);

    adapter=new ArrayAdapter<Item>(this, R.layout.agendalist, agenda);
    mAgenda.setAdapter(adapter);        
    mAgenda.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    //Load items into agenda
    initAgenda();
}

protected void updateDetails() {
    mRecipients.setText("This message will be sent to items " + (currentItemNum + 1) + " and later:");
    mSMS.setText(currentItem.getSMS());
}

protected void initAgenda() {
    currentItem = new Item();
    currentItem.setTitle("Reset Meeting");
    adapter.add(currentItem);
    setColour(0, Color.RED);
}

public void setColour(int pos, int col) {
    TextView tv = (TextView)mAgenda.getItemAtPosition(pos); //This is where the exception is thrown
    tv.setTextColor(col);
}
}

以下是ListView

的XML代码
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"  
    android:paddingTop="2dip" 
    android:paddingBottom="3dip"
    android:textSize="12pt" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" /> 

2 个答案:

答案 0 :(得分:2)

您需要创建自定义适配器,并在TextView.setTextColor();方法中使用getView,具体取决于您的着色标准。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null)
        convertView = View.inflate(context, layout, null);
    View row = convertView;

    TextView first = (TextView) convertView.findViewById(R.id.ListItem1);
    TextView second = (TextView) convertView.findViewById(R.id.ListItem2);
    if(condition == changecolor) {
        first.setTextColor(#FFFF0000);
        second.setTextColor(#FFFF0000);
    }
}

答案 1 :(得分:0)

你可以继承ArrayAdapter并在你的子类'getView方法中,你可以执行魔术

public View getView(int position, View convertView, ViewGroup parent) {
  TextView tv = super.getView(position, convertView, parent);

  if (position < 3) {     // I have just put dummy condition you can put your condition
    textView.setTextColor(colors);  // Here you can put your color
  } else {
    textView.setTextColor(colors);
  }
}