2017-08-10 51 views
0

我有一個按鈕(星期幾)的主菜單。如果參考一週中的這些日子將數據存儲在數據庫中,那麼它們將變成「綠色」。我理解SQL查詢本身,但不明白colourChange函數如何標識每個按鈕並'知道'如何更改它。有人可以解釋這是如何工作的?主菜單按鈕改變顏色,但不知道如何

MainMenu.java

private void colourChange() { 
    Cursor result = myDb.checkColour(); 

    if (result.getCount() == 0) {                 // If the result equals to 0 then do nothing. 
     // Default colour remains 

    } else { 
                            // if the result is not 0 then... 
     while (result.moveToNext()) {                // Move through each result... 
      String day = result.getString(0);              // and store the day (column 0) of the result in day 
      findViewById(getResources().getIdentifier(day + "button", "id", getPackageName()))  // Find the view by ID using getResources.getIdentifier and passing the following parameter (day) 
        .setBackgroundColor(getResources().getColor(R.color.colorSuccess));    // The variable colourSuccess stored in the colours.xml file sets the background colour green. 
     } 
    } 
} 

Database.java

public Cursor checkColour() {                  // a SELECT statement is used to SELECT DayOfWeek FROM RoutineTable and GROUP BY DayOfWeek and store this as result. 

    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor result = db.rawQuery("SELECT DayOfWeek FROM " + RoutineTable + " GROUP BY DayOfWeek", null); 

    return result; 
} 
+0

您是否嘗試過用調試器對其進行檢查並檢查變量? – litelite

+0

你的問題是什麼? – Milk

回答

0

讓我們來分解代碼。

getResources().getIdentifier(day + "button", "id", getPackageName()) 

Resources.getIdentifier()方法允許你訪問各種常數內R.java動態,通過名稱。 day + "button"是資源的名稱,"id"是資源的類型。所以這種方法將返回R.id.[day]button。如果day持有"sunday",那麼你將得到R.id.sundaybutton

findViewById([code from above]) 

現在getIdentifier()返回一個 「真實」 的ID給你(像R.id.sundaybutton),findViewById()將搜索你的佈局與android:id屬性的View對象。因此,如果您的佈局包含Viewandroid:id="@+id/sundaybutton",findViewById(R.id.sundaybutton)將返回它。

getResources().getColor(R.color.colorSuccess) 

Resources.getColor()採用彩色標識(在這裏R.id.colorSuccess)並返回顏色值(也許它是綠色的,也許0xFF00FF00)。

setBackgroundColor([color from above]) 

這一個是容易的:它設置指定View的背景顏色。

總之,你會在一週中的幾天和

  • 構建遍歷從周
  • 當天的標識使用標識
  • 取景得到的顏色值從你的資源
  • 該顏色值適用於創建視圖的背景

希望這有助於!

+0

優秀的答案。 10/10質量和細節。非常感謝你幫助我! :) – MarkW

0

下午好,

沒有看到所有的代碼爲應用這將是很難的資源文件信息給你一個明確的答案。查看代碼,它看起來像是將資源與查詢中返回的星期幾一起加上當前應用程序中的「按鈕」一詞。然後通過在顏色資源文件夾中查找名爲「colorSuccess」的資源來設置背景顏色,該資源將其更改爲綠色。

0

colourChange()函數首先請求數據庫返回爲光標。 while (result.moveToNext())正在循環而結果的所有行。

getResources().getIdentifier(day + "button", "id", getPackageName()) 

那找到指定的佈局資源id.Example "@+id/fridaybutton"

Accoriding Android的API文檔。函數參數在這裏。

getIdentifier(String name, String defType, String defPackage) 
相關問題