是否可以通过代码(java)更改整个应用程序或 Activity 的字体颜色?我想从共享首选项中读取颜色,然后更改 Activity 内的字体颜色。我已经为背景做到了这一点并且它有效,但我不知道如何全局更改字体。
public void usePreferences(){
SharedPreferences settings = getSharedPreferences(OptionListActivity.MY_PREFERENCES, MODE_WORLD_READABLE);
String backColorAsString = settings.getString(getResources().getString(R.string.background_color), "0");
Log.i(getResources().getString(R.string.font_color), backColorAsString);
int backColorRGB = 0;
if (backColorAsString.equals("RED"))
backColorRGB = Color.RED;
else if (backColorAsString.equals("BLUE"))
backColorRGB = Color.BLUE;
else if (backColorAsString.equals("GREEN"))
backColorRGB = Color.GREEN;
findViewById(android.R.id.content).setBackgroundColor(backColorRGB);
//works great till here
String fontColorAsString = settings.getString(getResources().getString(R.string.font_color), "0");
int fColorRGB = 0;
if (fontColorAsString.equals("RED"))
fColorRGB = Color.RED;
else if (fontColorAsString.equals("BLUE"))
fColorRGB = Color.BLUE;
else if (fontColorAsString.equals("GREEN"))
fColorRGB = Color.GREEN;
//WHAT TO DO NOW?
}
编辑:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
usePreferences();
}
最佳答案
第 1 部分
您可以创建自定义 TextView。为了最快地设置文本颜色,请在应用程序类中设置全局颜色。 (不是主要 Activity )
public class ColorTextView extends TextView {
private static int color = Color.BLUE;
public ColorTextView(Context context) {
super(context);
this.setTextColor(color)
}
public ColorTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTextColor(color)
}
public ColorTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setTextColor(color)
}
public static void setGlobalColor(int newcolor) {
color = newcolor;
}
}
并在 xml 中使用它,例如:
<your.package.name.ColorTextView
//other stuff
/>
最后,您可以在代码中设置颜色,如下所示:
ColorTextView.setGlobalColor(yourColor);
第 2 部分
设置如下所示的应用程序类,并将 usepreferences()
代码粘贴到其中。
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// paste code and set color here
}
}
最后,要运行此程序,您必须在应用程序标记的 list 中声明它:
android:name="your.package.name.MyApplication"
关于java - 通过代码(java)更改整个应用程序或 Activity 的字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22853386/