0

ImageView test = (ImageView) findViewById(R.id.A1);

gets me an ImageView

instead of A1 I would like to use a string variable to fetch a series of IDs

I have tried

Method Pmethod = Class.getDeclaredMethod("(ImageView) findViewById(Id.R." + dest.toString());

as suggusted in this question : how to call a java method using a variable name?

However I get the error

non-static method getDeclaredMethod cannot be referenced from a static context

Any way to fix this?

My latest attempt :

        String ps = "P"+ dest.toString();
        String ss = "S"+ dest.toString();
        int piecelayertier = getResources().getIdentifier(ps,"id","com.donthaveawebsite.mhy.ocfix");
        int selectorlayertier = getResources().getIdentifier(ss,"id","com.donthaveawebsite.mhy.ocfix");
        ImageView test =(ImageView)findViewById(piecelayertier);

        spot.TieAppearance((ImageView)findViewById(piecelayertier));
        spot.TieSelector((ImageView)findViewById(selectorlayertier));
Community
  • 1
  • 1
M Y
  • 1,831
  • 4
  • 24
  • 52
  • That's not how R works, and that's not how getDeclaredMethod works either. See the accepted answer to this question for more help with R: http://stackoverflow.com/questions/6804053/understand-the-r-class-in-android Since you have to do the work of defining the ids in your xml code, why do you need a dynamically generated list? As to getDeclaredMethod, the exception is exactly correct. You're trying to call it as if it's a static method. It's hard to tell what you want here and why you want it. – mttdbrd Apr 29 '15 at 04:46
  • @mttdbrd any idea why the ints aren't setting? The ps and ss strings are correctly populated and the resources exist. – M Y Apr 29 '15 at 05:24

1 Answers1

2

I think this is not a correct way to get id.

You can try following to get id using a string variable :

int id = getResources().getIdentifier("<String id>","id","<package name>");
ImageView test =(ImageView)findViewById(id);

You might also need to use a this reference like so :

int id = this.getResources().getIdentifier("<String id>","id", getPackageName());
M Y
  • 1,831
  • 4
  • 24
  • 52
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45