Android Studio,共享首选项设置文本颜色

Android Studio, Shared Preferences Set Text Color

目前我正在尝试 运行 这行代码:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle("Tell me");
    setContentView(R.layout.activity_post);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true)
    ;
    editText = (EditText) findViewById(R.id.editText1);
    textView = (TextView) findViewById(R.id.textView);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String s = sharedPreferences.getString("font_list", "null");
    Typeface face = Typeface.createFromAsset(getAssets(), "fonts/" + s);
    editText.setTypeface(face);

    String s2 = sharedPreferences.getString("font_size", "8");
    editText.setTextSize(Float.parseFloat(s2));

    String s3 = sharedPreferences.getString("font_color", "#000");
    editText.setTextColor(Color.parseColor(s3));



   // File directory = new File(path);
  // directory.mkdirs();
}

这是logcat图片

根据您记录的猫图像,您有 IllegalArgumentException 异常

您的颜色字​​符串格式不正确请参阅此 Color.parseColor

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'.

改变

String s3 = sharedPreferences.getString("font_color", "#000");

String s3 = sharedPreferences.getString("font_color", "#000000");
String s3 = sharedPreferences.getString("font_color", "#000000");

这样就对了。 否则使用 Color.NAME_OF_COLOR,这里介绍了很多。

In Android 您需要提供 6 或 8 HexaColor 代码。 因为它支持 RGB 或 ARGB。 在制作最终颜色时,每两个字符定义一次颜色的值。 喜欢:- #112233

11 define Red color with value 17 from (0 to 255 range)

22 define Green color with value 34 from (0 to 255 range)

33 define Blue color with value 51 from (0 to 255 range)

如果你有 alpha 而不是用 alpha 值定义前两位数,则相同:- 与 50% 不透明度相同,上述颜色 HexaValue 将是:- #80112233

where 80 is 128 alpha value from (0 to 255 range)

因此,您的问题的正确解决方案是:-

String s3 = sharedPreferences.getString("font_color", "#000000");

而不是

String s3 = sharedPreferences.getString("font_color", "#000");