Android and   in TextView

前端 未结 7 1966
一向
一向 2020-12-12 18:52

is it possible to add   in TextView? Has anyone achieved similar functionality?

I want to have non-breakable space in TextView.

相关标签:
7条回答
  • 2020-12-12 19:27

    It is possible to use   to have a readable solution. Including \u00A0 or   or  /  in the text doesn't really convey much information to the reader of the source code (or translator for that matter), unless you remember the hex codes. Here's a way to use the named entity in strings.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE resources [
        <!ENTITY nbsp "&#160;"><!-- non-breaking space, U+00A0 -->
    ]>
    <resources>
        ...
    </resources>
    

    This will create the missing declaration. The original HTML declaration can be found in https://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent referenced from the usual XHTML DTDs. All this works, because the XML parser reads these and substitutes while loading the file, so the entity won't be present in the resulting compiled resources.

    &nbsp; in Android Text (CharSequence) Resources

    <!-- Defined in <resources> -->
    <string name="html_text">Don\'t break <b>this&nbsp;name</b></string>
    
    <!-- Used in a layout -->
    <TextView
        android:layout_width="130dp"
        android:layout_height="wrap_content"
        android:background="#10000000"
        android:text="@string/html_text"
        />
    

    Device and preview (preview doesn't recognize HTML)

    &nbsp; in Android String (formatted) Resources

    <!-- Defined in <resources> -->
    <string name="formatted_text">%1$s is&nbsp;nice</string>
    
    <!-- Used in a layout -->
    <TextView
        android:layout_width="130dp"
        android:layout_height="wrap_content"
        android:background="#10000000"
        tools:text="@string/formatted_text"
        />
    

    Then in code:

    String contents = getString(R.string.formatted_text, "Using an &nbsp;");
    ((TextView)view.findViewById(android.R.id.text1)).setText(contents);
    

    Device and preview (preview doesn't recognize entities and Java strings are literal text!)

    Further tricks

    These are just example uses of DTD entities, use it base on your own preference.

    <!ENTITY con "\&apos;"><!-- contraction, otherwise error: "Apostrophe not preceded by \"
                                Sadly &apos; cannot be overridden due to XML spec:
                                https://www.w3.org/TR/xml/#sec-predefined-ent -->
    <!ENTITY param1 "&#37;1$s"><!-- format string argument #1 -->
    
    <string name="original">Don\'t wrap %1$s</string>
    <string name="with_entities">Don&con;t wrap &param1;</string>
    

    Both of them help highlighting:

    0 讨论(0)
提交回复
热议问题