2017-08-14 246 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

希望有所幫助。