如何更改特定列表项的背景颜色

时间:2014-05-09 18:40:28

标签: android listview sms android-arrayadapter

在下面的代码中,我在列表中添加了已发送和已接收的消息。现在我想在列表视图中显示它们,使得发送的消息必须具有不同的背景颜色,并且接收到具有不同背景颜色的消息,任何人都可以帮助。

            public List<String> getSMS() {

    List<String> sms1 = new ArrayList<String>();
    List<String> sms = new ArrayList<String>();
    sms2 = new ArrayList<String>();
    Uri uriSMSURI = Uri.parse("content://sms/");
   // Uri uriSMSURI1 = Uri.parse("content://sms/inbox");
    Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
    //Cursor cur1 = getContentResolver().query(uriSMSURI1, null, null, null,null);
    while (cur.moveToNext()) {
        int type = cur.getColumnIndex("type");
        String address = cur.getString(cur.getColumnIndex("address"));
        long  millis = cur.getLong(cur.getColumnIndexOrThrow("date"));
        String dat = (String) DateFormat.format("EEEE, MMMM dd, yyyy h:mm:ss aa", new Date(millis));
        String body = cur.getString(cur.getColumnIndexOrThrow("body"));
        int z=address.length();

        if (z==13)
        {
            address=address.substring(3, 13);
            address="0" + address;
            address = address.toString();

        }

        if (address.equals(str))
        {
            if(cur.getString(type).equalsIgnoreCase("1")){
                // sms received


                sms.add("Received: " + body + "\n" + dat);
             }
             else if(cur.getString(type).equalsIgnoreCase("2")){
                //sms sent
                 sms.add(" Sent: " + body + "\n" + dat);
             }
         }
}
    return sms;
}

1 个答案:

答案 0 :(得分:0)

您使用的是哪个Adapter? 如果您使用CursorAdapter,则可以在bindView()中执行此操作。这是一个粗略的示例代码:

TextView tv = null; 

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
      tv = (TextView) v.findViewById(R.id.itemname);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {

  if(condition1){
     tv.setBackgroundResource(R.color.white);
  }else{
     tv.setBackgroundResource(R.color.black);
  }

}

如果您使用任何其他适配器,则可以使用corresponding methods应用相同的逻辑。

相关问题