Skip to content
Advertisement

How to use strings on java (Android)

I’m working on a project where I’ve defined several strings to use on my project.

I want to use a string to be displayed as my subtitle of the page on the toolbar. The reason I’m using strings is because I want my app to be translation supported.

Here is how I use subtitles on the toolbar of my activity:

android.support.v7.app.ActionBar ab = getSupportActionBar();
    ab.setTitle("Title");
    ab.setSubtitle("Subtitle");

I want to use a string on java (like @string/helloworld in xml) but I don’t know how can I do that.

Can anyone help me?

Advertisement

Answer

In your “res” directory, there might be “strings.xml” file. (If you didn’t remove it). Add string tags like bellow code snippets.

<string name="title">Title Message</string>
<string name="sub_title">Sub Title Message</string>

And in your java file.

String mStringTitle = getString(R.string.title);
String mStringSubTitle = getString(R.string.sub_title);

You can also use these string resources in your layout XML like follows.

<TextView
    android:text="@string/title" />

For more information, please refer to the bellow URLs.

What is the string resource in Android? android_string_resources

How to support multiple locales? support_different_language // different-locales

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement