2011-12-04 77 views
2

因此,我正在爲Eclipse 4.0編程一個簡單的計算器,我正在嘗試對我的代碼進行流式處理,並儘可能簡化代碼。我試圖清理的地方是我的findViewById()。因爲我有按鈕0-9實例我有一個看起來像這樣的代碼十條線長塊:可以/我應該編輯R.java文件。如果是這樣,怎麼樣?

b0 = (Button) findViewById(R.id.b0); 
b1 = (Button) findViewById(R.id.b1); 
... 
b9 = (Button) findViewById(R.id.b9); 

正如你所看到的這個東西只是乞求一個for循環。所以我想做的是做兩個數組。在活動的一個實例變量數組它包含所有的數字鍵盤按鈕實例變量:

private Button[] numberPad = {b0,b1,b2,b3,b4,b5,b6,b7,b8,b9}; 

,然後在R.java文件中的ID類另一個數組保存所有按鈕的ID變量會看像這樣:

private static final int[] numberPad = {b0,b1,b2,b3,b4,b5,b6,b7,b8,b9}; 

的sooo我可以用這個循環減少十行按鈕實例的兩個:

for(int i = 0; i < numberPad.length; i++) 
    numberPad[i] = (Button) findViewById(R.id.numberPad[i]); 

當我鍵入了它的罰款,但WH我去保存它會自動恢復到它的原始形式。我沒有看到這個代碼有什麼問題。據我所知,它不會產生任何錯誤。爲什麼我不能以這種方式編輯R.java文件?有沒有辦法?我是不是該?

+0

看看http://stackoverflow.com/questions/3545196/android-programatically-iterate-through-resource-ids – Kennet

回答

2

正如前面所說,R文件是(或應是)重新生成上每次構建自動。你應該嘗試一些依賴注入框架(Roboguice適用於Android編程)來清理處理Views的問題。例如,而不是(從項目的資料爲準代碼):

class AndroidWay extends Activity { 
TextView name; 
ImageView thumbnail; 
LocationManager loc; 
Drawable icon; 
String myName; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    name  = (TextView) findViewById(R.id.name); 
    thumbnail = (ImageView) findViewById(R.id.thumbnail); 
    loc  = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
    icon  = getResources().getDrawable(R.drawable.icon); 
    myName = getString(R.string.app_name); 
    name.setText("Hello, " + myName); 
}} 

您可以使用更簡單和更短的版本:

class RoboWay extends RoboActivity { 
@InjectView(R.id.name)    TextView name; 
@InjectView(R.id.thumbnail)  ImageView thumbnail; 
@InjectResource(R.drawable.icon) Drawable icon; 
@InjectResource(R.string.app_name) String myName; 
@Inject       LocationManager loc; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    name.setText("Hello, " + myName); 
} } 

這不僅有助於保持你的意見的管理清潔,就地,但也在測試時非常有幫助。

+0

喜歡這個答案。謝謝 – Dave

1

的R.java文件是重新創建。

0

你可以找到你的答案here

0

即使你沒有嘗試這種方法,你將不得不使用反射,以獲得「findViewbyID」爲(R.id.numberPad [1])現在沒有反思工作。

不使用任何的反思,雖然會neaten你的代碼是非常緩慢的。

0

你知道,你可以實現所有外部的 R.java文件和你自己的類 - 只需做一個靜態導入R.id. *。

0

R.java是一個可自動生成的系統生成文件。你不應該嘗試手動編輯它。

相關問題