好吧,问题是。在我的 Android 应用程序中,我有两个单独的 Activity 用于选项和主要 Activity 。主 Activity 中有一个地方,用于检查选项的更改并应用样式。它看起来像这样:
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 .
最佳答案
我假设您复制了 SetThemeX
方法中的大部分代码。因此,我建议引入一个捕获主题本质的类并使用它:
class MyTheme {
public int background;
public int alpha;
public int color;
public MyTheme(int background, int alpha, int color) {
this.background = background;
this.alpha = alpha;
this.color = color;
}
}
制定一种方法来设置主题:
public void setTheme(DTypeActivity dTypeActivity, MyTheme theme) {
final EditText edit_text = (EditText) findViewById(R.id.editText1);
final View main_view = (View) findViewById(R.id.mainview);
main_view.setBackgroundDrawable(getResources().getDrawable(theme.background));
edit_text.getBackground().setAlpha(theme.alpha);
edit_text.setTextColor(getResources().getColor(theme.color));
}
并在存储这些主题的地方保留一张 map :
Map<Integer, MyTheme> themes = new HashMap<>();
themes.put(1, new MyTheme(R.drawable.grey_background, 0, R.color.DrText));
// put other themes
在您的 SetApplicableStyle
方法中,您可以简单地使用
public void SetApplicableStyle (DTypeActivity dTypeActivity, int theme, int font, int size) {
setTheme(dTypeActivity, themes.get(theme);
// set font and size similarly
}
关于java - 如何处理多个Android方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16166381/