由於在程式碼中指定顏色值不是好習慣、不夠彈性,所以示範的程式碼會從指定的 Theme 中取出 colorPrimary 及 colorPrimaryDark 二項屬性的內容,並分別套用到 App Bar 及 Status Bar。另外,示範的程式碼使用的是衍生自 AppCompatActivity 的 Activity,所以在取得 Action Bar 的 Instance 時呼叫的是 getSupportActionBar()。
完整的程式碼如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void changeActionBarColor(int inThemeId) { | |
ActionBar actionBar = getSupportActionBar(); | |
if (actionBar != null) { | |
String primaryColor = null; | |
String primaryColorDark = null; | |
primaryColor = this.getThemePrimaryColor(inThemeId); | |
primaryColorDark = this.getThemePrimaryColorDark(inThemeId); | |
if (primaryColor != null && primaryColor.length() > 0) { | |
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(primaryColor))); | |
} | |
if (primaryColorDark != null && primaryColorDark.length() > 0) { | |
Window window = this.getWindow(); | |
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); | |
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); | |
window.setStatusBarColor(Color.parseColor(primaryColorDark)); | |
} | |
} | |
} | |
private String getThemePrimaryColor(int inThemeId) { | |
String result; | |
int[] attrs = {R.attr.colorPrimary}; | |
TypedArray typedArray = obtainStyledAttributes(inThemeId, attrs); | |
result = typedArray.getString(0); | |
typedArray.recycle(); | |
return result; | |
} | |
private String getThemePrimaryColorDark(int inThemeId) { | |
String result; | |
int[] attrs = {R.attr.colorPrimaryDark}; | |
TypedArray typedArray = obtainStyledAttributes(inThemeId, attrs); | |
result = typedArray.getString(0); | |
typedArray.recycle(); | |
return result; | |
} |
0 意見:
張貼留言