2017-08-14 295 views
0

伙计!我有一个for循环的问题。所以我有一个for(),通过数据库中第三列的每个值(这应该是日期格式)。我想改变列表视图中的项目的背景颜色if添加日期的月份是一样的电流month.The问题是存在的 - 如果我使用这样的代码:For循环和if语句

public void setItemRed(View view){ 

    for(int i = 0 ; i <= myDB.getLastID() ; i++){ 
     String date = myDB.getcol3(i); 
     String day = date.substring(0 , 2); 
     String month = date.substring(3 , 5); 
     String currentDate = currentDate(); 
     String currentMonth = currentDate.substring(3 , 5); 

     listView.getChildAt(i).setBackgroundColor(Color.RED); 
    } 

} 

一切工作和每一个项目获得红background.But当我添加如果:

public void setItemRed(View view){ 

    for(int i = 0 ; i <= myDB.getLastID() ; i++){ 
     String date = myDB.getcol3(i); 
     String day = date.substring(0 , 2); 
     String month = date.substring(3 , 5); 
     String currentDate = currentDate(); 
     String currentMonth = currentDate.substring(3 , 5); 
     if(date.length() == 10){ 
      if(month == currentMonth) { 
       listView.getChildAt(i).setBackgroundColor(Color.RED); 
      } 
     } 
    } 

} 

它不起作用。提前谢谢!

+1

尝试在'if语句'中整理你的缩进。 – 2017-08-14 07:28:54

+0

'month == currentMonth'将始终返回false。使用'month.eqauals(currentMonth)'代替 – mihail

+0

谢谢mihail!解决!但重要的是为什么它总是返回假? – Goshoy

回答

0

每当比较两组字符串时,您需要使用.equals()命令。简单地通过使month == currentMonth不起作用并返回false。

因此请尝试用month.equals(currentMonth)代替month == currentMonth

希望有所帮助。