繁体   English   中英

通过代码更改整个应用程序或活动的字体颜色(java)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM