Skip to content

Instantly share code, notes, and snippets.

@Neuraln
Created April 11, 2018 14:31
Show Gist options
  • Save Neuraln/302eb7d0178d2ac689e5646a713c8377 to your computer and use it in GitHub Desktop.
Save Neuraln/302eb7d0178d2ac689e5646a713c8377 to your computer and use it in GitHub Desktop.
Building a resource ID as a string
Here's my strings.xml
---------------------------------------
<resources>
<string name="app_name">Scratch Pad</string>
<string name="hello_world">Hello World!</string>
<string name="text_1">text one</string>
<string name="text_2">text two</string>
<string name="text_3">text three</string>
<string name="text_4">text four</string>
<string name="text_5">text five</string>
</resources>
-----------------------------------------
Here's my activity_main.xml
-----------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="32sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
-----------------------------------------
and here's my MainActivity.java
-----------------------------------------
package com.example.android.scratchpad;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// I want to get the string named "text_2" from strings.xml
int num = 2;
// Here I'm building my ID as a string instead of hardcoding it like R.string.text_2
String textID = "text_" + num;
int resID = getResources().getIdentifier(textID, "string", getPackageName());
// Now I'm grabbing the value of string "text_2" from strings.xml and putting it into changed_text
String changed_text = (String) getText(resID);
/**
* Changing the "hello world" text in text_view to the value of changed_text
*/
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(changed_text);
}
}
-----------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment