Zuop Zuop - 3 years ago 235
Android Question

Hide String placeholder when using initial String from xml

this question is regarding the String placeholder mechanic in Android. There are plenty of posts about "how can I use placeholders" etc, but my question is quiet different (or I'm just plain stupid) and I can't find an answer on the web.

How can I hide the placeholder in a String resource when I'm referencing it via an xml file?

The point is, if I have a String resource like

<string name=mystring>There comes the placeholder: %s</string>


and I use it in my whatever.xml file and set the text of a TextView to android:text="@string/mystring" then it actually really displays "There comes the placeholder: %s". But you can imagine I want to avoid that the users see "%s" ;-)

So how do we do that?

Cheers

Answer Source

The %s in your string is not just a placeholder, it is a format specifier. You can read all about them here: https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

The short answer to your question is that it is not possible to hide this format specifier from your users. However, that is because strings with format specifiers in them should not be used as simple arguments to android:text attributes.

The correct use of these string resources is to populate the text of your TextView at runtime (in Java) using Resources.getString(int id, Object... formatArgs) (or Activity.getString(int id, Object... formatArgs)), at which time you will pass in the real value to be substituted into your string.

Using the naming from your example, you might have something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView myTextView = (TextView) findViewById(R.id.mytextview);
    myTextView.setText(getString(R.string.mystring, "real value"));
}

Note that you can use tools:text="@string/mystring" in your layout to see the string at design time (though this will still include any format specifiers). Real users will never see this text, though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download