2015-03-13 24 views
2

如何在buttonclick上調用setStatusBarColor?我有事件監聽器代碼,但我不確定如何調用此方法。我試圖在點擊按鈕時更改狀態欄的顏色。調用setStatusBarColor ANDROID

這裏是我的代碼:

public static void setStatusBarColor(Activity activity, int statusBarColor) { 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
        // If both system bars are black, we can remove these from our layout, 
        // removing or shrinking the SurfaceFlinger overlay required for our views. 
        Window window = activity.getWindow(); 
        if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) { 
         window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
        } else { 
         window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
        } 
        window.setStatusBarColor(Color.parseColor("#4CAF50")); 
       } 
      } 

這裏是我的按鈕偵聽

public void addButtonListener() { 

     Button = (Button) findViewById(R.id.Button); 
     Button.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       setStatusBarColor(); 
      } 
     }); 
    } 
+0

你能解釋一下什麼是不工作的參數? – 2015-03-13 14:28:27

+0

在您的按鈕上至少顯示偵聽器代碼。 – 2015-03-13 14:31:57

+0

道歉@ci_。我試圖用setStatusBarColor()來調用它。 – user1353517 2015-03-13 14:50:04

回答

7

你的方法調用改成這樣

在活動

public void onClick(View view) { 
    setStatusBarColor(this, Color.parseColor("#4CAF50")); 
} 

在片段:

public void onClick(View view) { 
    setStatusBarColor(getActivity() , Color.parseColor("#4CAF50")); 
} 

或刪除方法

public void onClick(View view) { 
    setStatusBarColor(); 
} 

public static void setStatusBarColor() { 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
     // If both system bars are black, we can remove these from our layout, 
     // removing or shrinking the SurfaceFlinger overlay required for our views. 


     //change here 
     Window window = activity.getWindow(); 

     // By -->>>>> Window window = getWindow(); 

     //or by this if call in Fragment 
     // -->>>>> Window window = getActivity().getWindow(); 


     int statusBarColor = Color.parseColor("#4CAF50"); 

     if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) { 
      window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
     } else { 
      window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
     } 
     window.setStatusBarColor(statusBarColor); 
    } 
} 
+0

我試圖從方法中刪除參數,但我面臨着「無法解析符號」活動「」和「無法解析符號statusBarColor – user1353517 2015-03-13 15:35:35

+0

我也嘗試了第二種方法,我面臨無法解決方法getActivity()和第一種方式表示它不能應用 – user1353517 2015-03-13 15:36:29

+0

answer updated =) – 2015-03-13 15:36:53

相關問題