问题描述
我有<string name="monthly_savings_other">Monthly savings\n$%1$d</string>
,我知道因为%1$d
我不能像字符串一样显示它。但是我不知道如何正确格式化,尽管互联网上有很多例子我只能把头缠起来。我不知道该如何服用%1$d
从android中的字符串文件夹中对其进行格式化。
public void binding(final OtherAccModel modelClass) {
binding.setother(modelClass);
binding.executePendingBindings();
setSpannableTextWithColor(binding.policyTV,R.string.policy_account_number_other,modelClass.getPolicy(),Color.BLACK);
setSpannableTextWithColor(binding.companyNameTV,R.string.company_name_other,modelClass.getCompanyName(),Color.BLACK);
setSpannableTextWithColor(binding.monthlySavingsTV,R.string.monthly_savings_other,String.valueOf(modelClass.getMonthlySavings()),Color.BLACK);
setSpannableTextWithColor(binding.rorTV,R.string.return_of_value_other,String.valueOf(modelClass.getRor()),Color.BLACK);
setSpannableTextWithColor(binding.accNameTV,R.string.type_other,modelClass.getType(),Color.BLACK);
setSpannableTextWithColor(binding.accValueTV,R.string.current_value_other,String.valueOf(modelClass.getCurrentValue()),Color.BLACK);
}
void setSpannableTextWithColor(TextView view,int resourceId,String string,int color) {
if (string == null)
return;
String fulltext = context.getResources().getString(resourceId,string);
String part = string;
SpannableString str = new SpannableString(fulltext);
str.setSpan(new ForegroundColorSpan(color),fulltext.length() - part.length(),fulltext.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(str);
}
第String fulltext = context.getResources().getString(resourceId,string);
行,我遇到了错误
java.util.IllegalFormatConversionException: d != java.lang.String
解决方法
使用%1 $ s代替%1 $ d。
d将数字格式化为十进制数字,并且只能与整数一起使用
有关更多信息,请阅读https://developer.android.com/guide/topics/resources/string-resource#FormattingAndStyling