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); 

     

  • 相关阅读:
    Oracle Flashback技术
    管理Redo Log
    管理UNDO
    Oracle利用PIVOT和UNPIVOT进行行列转换
    如何在SQL CASE表达式中返回多个值
    第二十八节 jQuery事件委托
    第二十七节 jQuery弹框练习
    第二十六节 jQuery中的事件冒泡
    第二十五节 jQuery中bind绑定事件和解绑
    第二十四节 jQuery中的resize事件
  • 原文地址:https://www.cnblogs.com/liuyunfeifei/p/2781925.html
Copyright © 2011-2022 走看看