2016/8/4

如何使用程式更改 Activity 中 App Bar 的背景顏色

一般在設計 Activity 時,會設定 Activity 的佈景主題,也就是套用某一個特定的 Theme。如果今天在啟動 Activity 後想要動態調整 App Bar 的背景顏色,可以在另外指定 Activity 所套用的 Theme 後重新啟動 Activity。然而,這樣的程序只是為了換個顏色似乎有一點小題大作,所以在這篇文章中提供了另外一種不用重新啟動 Activity 的方法。

由於在程式碼中指定顏色值不是好習慣、不夠彈性,所以示範的程式碼會從指定的 Theme 中取出 colorPrimary 及 colorPrimaryDark 二項屬性的內容,並分別套用到 App Bar 及 Status Bar。另外,示範的程式碼使用的是衍生自 AppCompatActivity 的 Activity,所以在取得 Action Bar 的 Instance 時呼叫的是 getSupportActionBar()。

完整的程式碼如下:

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;
}
view raw Activity.java hosted with ❤ by GitHub






0 意見:

張貼留言