Domanda

As an exercise, I am building a calendar. Below is a small segment of my code. I have a class MyCalendar that extends Activity. This Activity will be linked to an XML file whose layout includes seven TextViews with ids R.id.day0 thru R.id.day6.

If converted from String to int, will the Activity's findViewById() method recognize the int version of these ids?

        String Days [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        TextView dayViews [];

        private void populateViews (){

            for (int counter = 0; counter < Days.length; counter++){
                int ID = Integer.parseInt("R.id.day"+counter);
                dayViews [counter] = (TextView) findViewById(ID);
                dayViews[counter].setText(Days[counter]);
            }
È stato utile?

Soluzione

I have not tried it myself. but this answer https://stackoverflow.com/a/11595723/1514861 suggest you can do it like this:

private String getStringResourceByName(String aString) {
  String packageName = getPackageName();
  int resId = getResources().getIdentifier(aString, "string", packageName);
  return getString(resId);
}

EDIT: I think you would also need to replace "string" with "id"

Altri suggerimenti

Definitely not. R class from Java are ids generated at compilation.

I would do:

final int[] days = { R.id.day0, R.id.day1, ... };
for (int day : days) {
    // ...
}

NO, int ID = Integer.parseInt("R.id.day"+counter);, what you did in there is making a representation of String to Integer, not an actual mapping from R class to xml resource.

I know that's an old question, but it might help more people. What you can do is to call getIdentifier(), like our friends said. For that, you'll need to call it inside a loop, inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:

Your resources file:

R.string.string0
R.string.string1
R.string.string2
...
R.string.string9

In java:

for (i=0;i<10;i++){
    int resourceId = getResources().getIdentifier("string"+i, "string", this.getPackageName())
    println(getResources().getString(resourceId));
}

Then, in your rescourceId variable, you'll have an equivalent to: R.string.string0 to R.string.string9. And, in println, you'll have the value correspondent of your resources string.

In Kotlin:

for (i in 0..10){
    val resourceId = this.resources.getIdentifier("string"+i, "string", this.packageName)
    println(resources.getString(resourceId))
}

With the same explanation that I said before.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top