zoukankan      html  css  js  c++  java
  • android中的格式化字符串

    格式化字符串示例

    在strings.xml文件中定义:

    <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

    Java代码:

    TextView textView = (TextView) findViewById(R.id.text);
    textView.setText(String.format(getResources().getString(R.string.welcome_messages), "LiLei", 1));
     
    关于string 
    下面是官方给出的正确/错误的例子:

    //不使用转义符则需要用双引号包住整个string 
    <string name="good_example">"This'll work"</string> 
    //使用转义符 
    <string name="good_example_2">This\'ll also work</string>
    //错误 
    <string name="bad_example">This won't work!</string> 
    //错误 不可使用html转义字符 
    <string name="bad_example_2">XML encodings won&apos;t work either!</string>
     
    对于带格式的string,例如在字符串中某些文字设置颜色,可以使用html标签。对于这类型的string,需要进行某些处理,在xml里面不可以被其他资源引用。官方给了一个例子来对比普通string和带格式string的使用:
    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <string name="simple_welcome_message">Welcome!</string> 
        <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> 
    </resources> 
    Xml代码:
    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:textAlign="center" 
        android:text="@string/simple_welcome_message"
    />
    Java代码:
    // Assign a styled string resource to a TextView on the current screen. 
    CharSequence str = getString(R.string.styled_welcome_message); 
    TextView tv = (TextView)findViewByID(R.id.text); 
    tv.setText(str); 
    另外对于带风格/格式的string的处理,就麻烦一点点。官方给了一个例子:
    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
      <string name="search_results_resultsTextFormat">%1$d results for &lt;b>&amp;quot;%2$s&amp;quot;&lt;/b></string> 
    </resources> 
    这里的%1$d是个十进制数字,%2$s是字符串。当我们把某个字符串赋值给%2$s之前,需要用htmlEncode(String)函数处理那个字符串:
    //title是我们想赋值给%2$s的字符串 
    String escapedTitle = TextUtil.htmlEncode(title); 
    然后用String.format() 来实现赋值,接着用fromHtml(String) 得到格式化后的string:
    String resultsTextFormat = getContext().getResources().getString(R.string.search_results_resultsTextFormat); 
    String resultsText = String.format(resultsTextFormat, count, escapedTitle); 
    CharSequence styledResults = Html.fromHtml(resultsText); 

     

  • 相关阅读:
    HTML <input> 标签的 maxlength 属性
    HTTP 方法:GET 对比 POST
    怎么在html页面和js里判断是否是IE浏览器
    一行神奇的javascript代码
    c# 数据库批量插入数据SqlBulkCopy 示例
    c# 多线程调用窗体上的控件 示例
    sqlserver查找使用了某个字段的所有存储过程
    SQL Server 数据库性能优化
    SQL语句的执行过程
    Sql Server- 性能优化辅助指标SET STATISTICS TIME ON和SET STATISTICS IO ON
  • 原文地址:https://www.cnblogs.com/liuyunfeifei/p/2781925.html
Copyright © 2011-2022 走看看