1

I was trying to save time by using a for loop to initialize all the sprites i wanted on screen. I had a couple of images on my drawable folder. So I renamed them accordingly. I wanted to concatenate the i to the expression, then it had to be called/invoked somehow! At first I thought about doing this:

Integer.parseInt("R.drawable.scoredisplay" + i)

Then, of course you cant parse that into an integer, also the result of that expression returns an integer anyway. How can I make the concatenation of the expression with i and then call it? is it possible?

4

1 回答 1

1

It's possible, you need to do the following:

Context x = getApplicationContext();
int myId  = x.getResources().getIdentifier("R.drawable.scoredisplay" + i, "drawable",x.getPackageName());

Where the first parameter is the id as String of the View you want to get, the second one is the type of resource in this case "drawable", and the third one the package name which we obtain also from the context, calling getPackageName() method. Then afterwards you can get the view with the following code:

View myView = findViewById(myId);

Casting the string to an integer as you were thinking makes no sense, since the id is not a string (although it has a workaround like I'm showing you).

Update

Since you are using this code outside of an Activity class the calls to the Context methods are not valid. You need to create a way of accessing the Activity Context from outside of the activity (you mention calling .getContext() from your class, but that will get that classes context, not the activity). A way of achieving this would be modifying your constructor, lets say you have a class named myClass:

class myClass{
    //Declase a Context variable inside your class
    Context x;

    //You implement a constructor for this class that accepts a Context as 
    //a parameter (feel free to add more if you are using a constructor already)
    public myClass(Context applicationContext){
        //Assign the passed value to your local Context
        x = applicationContext;
    }

    //Afterwards, on a different part of your class, you could invoke activity 
    //related methods by using the Context you have 'x'
    public void otherMethod(){
       int myId  = x.getResources().getIdentifier("R.drawable.scoredisplay" + i, "drawable",x.getPackageName());
    }
}

The last part in ensuring you are passing your value correctly from your Activity, you should see something similar to this somewhere in your code:

myClass i = new myClass();

Since we now have a constructor, or have modified the existing one, you can add this to pass the activity context right into your game or whatever class your creating:

myClass i = new myClass(this);//'this' can be 'getApplicationContext()'
于 2012-11-16T00:47:44.407 回答