0
好的,問題是。在我的Android應用程序中,我有兩個單獨的活動供選項和主要活動使用。主要活動中有一個地方,它檢查選項的變化並應用樣式。它看起來像這樣:如何處理多個Android方法?
if (prefs.getBoolean("opt_changed", true)) {
Theme = prefs.getInt("theme", Theme);
Font = prefs.getInt("font", Font);
Size = prefs.getInt("size", Size);
SetApplicableStyle(this, Theme, Font, Size);
/** Setting opt_changed to false. */
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("opt_changed", false);
editor.commit(); // apply changes
}
SetApplicableStyle
方法,這裏所說的,看起來是這樣的:
public void SetApplicableStyle (DTypeActivity dTypeActivity, int Theme, int Font, int Size) {
// Retrieving the EditText and the View as objects
final EditText edit_text = (EditText) findViewById(R.id.editText1);
final View main_view = (View) findViewById(R.id.mainview);
// Setting the theme
switch(Theme){
case 1:
SetThemeLight (this);
break;
case 2:
SetThemeBlue (this);
break;
case 3:
SetThemeDark (this);
break;
}
// Setting the font
switch(Font){
case 1:
SetFontSans (this);
break;
case 2:
SetFontSerif (this);
break;
case 3:
SetFontMono (this);
break;
}
// Setting the size
switch(Size){
case 1:
SetSizeSm (this);
break;
case 2:
SetSizeMd (this);
break;
case 3:
SetSizeBg (this);
break;
}
}
的,它的Set[Something][Somewhat]
方法的例子,有SetThemeLight
一個:
public void SetThemeLight (DTypeActivity dTypeActivity) {
final EditText edit_text = (EditText) findViewById(R.id.editText1);
final View main_view = (View) findViewById(R.id.mainview);
main_view.setBackgroundDrawable(getResources().getDrawable(R.drawable.grey_background));
edit_text.getBackground().setAlpha(0);
edit_text.setTextColor(getResources().getColor(R.color.DrText));
}
我的問題涉及在這個簡單的應用程序中使用的方法的數量。我一直在考慮減少代碼量並實施SetApplicableStyle
方法。現在我正在考慮擺脫Set[Something][Somewhat]
是否合適,並將它們的線路直接連接到SetApplicableStyle
交換機的情況。我主要關心的是方法的數量,但我知道,巨大的方法也是一種不好的做法。這裏更好的解決方案是什麼?全部源代碼可用here。
我只會建議把HashMap放到一個單獨的方法'lookupStyle'或類似的東西,並在'setApplicableStyle'方法中使用它,因爲我看不到任何其他方式可以從任何地方訪問地圖。如果我在'OnCreate'中聲明地圖,我無法從'OnResume'訪問它,但是我都需要它。無論如何謝謝你的想法。 – wswld 2013-04-23 12:29:41
@VsevolodGlumov是的,你應該讓地圖在某種程度上全局可訪問。我在回答中忽略了這一點,因爲它完全取決於您的應用程序的結構。我記得我曾經創建過一個android應用程序時使用了一個全局應用程序上下文對象,但是如果這個進程被釋放以釋放資源,這可能會帶來麻煩。 – 2013-04-23 12:41:32