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