2011-12-31 7 views
1

可能複製する整数変換、forループ内の変数の宣言:ストリング(アンドロイド/ジャワ)


Android findViewbyId with a variant string

Iアクティビティ内のコードのこのタイプを持っています

ImageButton button1 = (ImageButton)findViewById(R.id.butid1); 
ImageButton button2 = (ImageButton)findViewById(R.id.butid2); 
ImageButton button3 = (ImageButton)findViewById(R.id.butid3); 

ここでは、これらの変数をforループ内で宣言したいと考えています。また、これらのN個のボタンでアクションがとられます。例:

for (int NUMBER = 1; NUMBER <= N; NUMBER++) { 
    ImageButton button"NUMBER" = (ImageButton)findViewById(R.id.butid"NUMBER"); 
    button"NUMBER".setEnabled(false); 
} 

Nはさまざまな状況によって変化します。これを解決するにはどうしたらよいですか? (P.S.「類似のタイトルの質問」で結果が見つかりませんでした)

+0

ボタンの配列を使用しないのはなぜですか?またはarraylist Nが変数の場合 – prongs

+0

私はAndroid用の小さなスタートプログラムをやっていましたが、それほど多かったわけではありません。しかし、あなたはImageButtonのような配列を使うことはできません[] button = new ImageButton [3];ボタン[i] =(ImageButton)findViewById(R.id.butid + Integer.toString(i))を使用します。よろしくお願いします。 –

+0

ここで同じ質問:http://stackoverflow.com/questions/6679434/android-findviewbyid-with-a-variant-string –

答えて

2

すべてのボタンをボタン配列に入れてください。だから、あなたは単にあなたが好きなように配列を反復することができます。

ImageButton[] buttons = new ImageButton[<put here the total number of Buttons>]; 

buttons[0] = (ImageButton)findViewById(R.id.butid1); 
buttons[1] = (ImageButton)findViewById(R.id.butid2); 
... 
buttons[N-1] = (ImageButton)findViewById(R.id.butidN); 

for (int i = 0; i < N; i++) { 
    buttons[i].setEnabled(false); 
} 
+0

私の編集をしないでください。それは両方の作品...私はひどいです:P – schijndelvanjos

0

使用ImageButton[] button = new ImageButton[NUMBER]してからループがあるべきために:

for (int i = 0; i < NUMBER; i++) { 
    ImageButton button[i] = (ImageButton)findViewById(R.id [***]); 
    button[i].setEnabled(false); 
} 

[*]私は、Androidを知らないが、私のようにすべてのボタンを取得する方法があると想像いくつかの種類のリストまたは配列を使用して、それぞれIdにアクセスする必要はありません。