2015-04-29 33 views
0

ImageView test = (ImageView) findViewById(R.id.A1);如何使用一個變量名

得到我的ImageView的

代替A1的我想用一個字符串變量來獲取一系列的ID

我去取Java中的R ID已試圖

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

在這個問題suggusted:how to call a java method using a variable name?

但是我得到的錯誤

非靜態方法getDeclaredMethod不能從靜態上下文

任何方式來解決這個引用?

我的最新嘗試:

 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)); 
+0

這不屬於R是如何工作的,這不是getDeclaredMethod如何工作。看到這個問題的公認的答案更多的幫助與R:http://stackoverflow.com/questions/6804053/understand-the-r-class-in-android因爲你必須做的定義在你的XML中的ID的工作代碼,爲什麼你需要一個動態生成的列表?至於獲得聲明的方法,異常是完全正確的。你試圖把它稱爲靜態方法。很難說出你想要的東西以及爲什麼你想要它。 – mttdbrd

+0

@mttdbrd任何想法爲什麼整數不設置? ps和ss字符串正確填充並存在資源。 – hellyale

回答

2

我覺得這是不是拿到ID的正確途徑。

你可以嘗試以下使用字符串變量來獲得ID:

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

您可能還需要使用this參考,像這樣:

int id = this.getResources().getIdentifier("<String id>","id", getPackageName()); 
+0

這幾乎是我所需要的,除了'int id'沒有被設置。 – hellyale

+0

@hellyale自從爲我工作之後,你會得到任何異常。 –

+0

沒有例外,值總是設置爲0. – hellyale

相關問題