網易新聞有一個小功能,功能雖小,但看的出來大公司的產品設計確實很不錯,今天就實現下改功能,如果用戶點擊選擇瞭夜間模式或者日間模式,那麼所有的activity背景都要變,其實android源碼給每個activity 內容區域都定義瞭一個id,就是android.R.id.content,因為所有的activity背景要變色,因此肯定要寫一個基類,代碼如下:
public class BaseActivity extends Activity { protected void onCreate(android.os.Bundle savedInstanceState) { super.onCreate(savedInstanceState); }; @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); (((ViewGroup) findViewById(android.R.id.content)).getChildAt(0)).setBackgroundColor(getResources().getColor( true ? R.color.root_view_background_color_night : R.color.root_view_background_color)); } }
用戶點擊日間或者夜間模式,肯定是存儲一個值到SharedPreferences中,我在上面的代碼中是寫瞭true,如果真實的項目中肯定是從SharedPreferences文件中讀取,就是這樣瞭,簡單吧!