Skip to content

StringHelper

Ade Fruandta edited this page Apr 25, 2018 · 2 revisions

Basicaly string helper will call Context.getString, but in our string we can put another resource string like below

<string name="app_name">HappySupportAndroid</string>
<!-- {@string/app_name} will be replace into HappySupportAndroid -->
<string name="hallo">Hallo {@string/app_name}</string>

For support that, we just call get string with StringHelper like below

class MainActivity : AppCompatActivity() {
  
  ...
  
  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        ...
        
        StringHelper.getString(this, R.string.hallo)
        
        // using kotlin extentions
        getStringHelper(R.string.hallo)
        
        ...
        
    }

  ...
  
}

We also support formatArgs and another resource will be read as string.

<color name="colorPrimary">#3F51B5</color>

<string name="app_name">HappySupportAndroid</string>
<string name="hallo">Hallo {@string/app_name} %1$s</string>
<!-- {@color/colorPrimary} will be replace into #3f51b5 -->
<string name="hallo_2"><![CDATA[Hi %1$s %2$d <b>{@string/hallo}</b> <font color="{@color/colorPrimary}">{@color/colorPrimary}</font>]]></string>
class MainActivity : AppCompatActivity() {
  
  ...
  
  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        ...
        
        StringHelper.getString(this, R.string.hallo_2, arrayOf("Happy", 2), arrayOf("Fresh"))
        
        // using kotlin extentions
        getStringHelper(R.string.hallo_2, arrayOf("Happy", 2), arrayOf("Fresh"))
        
        ...
        
    }

  ...
  
}
Clone this wiki locally