[英]Q: Android - Setting Font Color of entire Activity Programmatically with NO XML
[英]Changing font color for entire application or activity via code(java)
是否可以通過代碼(java)更改整個應用程序或活動的字體顏色? 我想從共享首選項中讀取顏色,然后更改活動內的字體顏色。 我已經為背景做了這個,它的工作原理,但我不知道如何更改字體全球。
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。 要使文本顏色設置得最快,請在應用程序類中設置全局顏色。 (不是主要活動)
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
}
}
最后,要運行它,您必須在應用程序標記中的Manifest中聲明它:
android:name="your.package.name.MyApplication"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.