Jakub
Jakub

Reputation: 2141

How do I get a String from XML by name reference?

I'm trying do something like this

public class CytatCore {

    public static void cytatCore(int number, TextView tv) {

       tv.setText(R.string.text+number);
    }
}

I've a lot of string in xml named e.g "text1", "text2" etc. Only last value is changing. I tried to do this in couple ways, but I still get errors in code.

Upvotes: 0

Views: 102

Answers (4)

user
user

Reputation: 87064

Another option you have is to get a reference to the Resources object and use the method getIdentifier(). If you are in an activity then you could do:

public void cytatCore(int number, TextView tv) {    
    int id = getResources().getIdentifier("text" + 1, "string", this.getPackageName());
    t.setText(id);
}

Upvotes: 1

Jason Robinson
Jason Robinson

Reputation: 31283

I'm a bit confused on what you're trying to accomplish because your question is not written clearly, but I'll take a stab in the dark and assume your question is

How do I append a number onto the end of a string I have in XML?

Edit: My assumption was wrong, it appears your question is rather

How do I get a String from XML by name reference?

Using the getIdentifier() method of a Context will look up an ID by name...but be warned that this operation is not recommended if it's used extremely often, as it's slow.

public class CytatCore {

    public static void cytatCore(Context context, int number, TextView tv) {

       int textId = context.getResources().getIdentifier("text" + number, "string", context.getPackageName());
       tv.setText(textId);
    }
}

Upvotes: 2

Chintan Raghwani
Chintan Raghwani

Reputation: 3370

I think followin code wil work for you

switch(number) {
    case 1 : tv.setText(R.string.text1);
    case 2 : tv.setText(R.string.text2);
}

while using this type code, put also text1, text2 in your R.string; switch case also processed faster.

Upvotes: 3

Marcos
Marcos

Reputation: 4643

Try putting the names in an array:

...
private String[] ids = new String[N];
for (int i = 0; i < N; i++) {
    ids[i] = context.getString(R.string.resource_name) + i;
}

and then:

...
public static void cytatCore(int i, TextView tv) {
    tv.setText(ids[i]);
}

or simply:

    ...
public static void cytatCore(int i, TextView tv) {
    tv.setText(context.getString(R.string.resource_name) + i);
}

Upvotes: 0

Related Questions