2016-08-17 4 views
2

私はこのコードを持っています。Androidでアンドロイド:idを配列として宣言できますか?

rele[0] = new ReleController(findViewById(R.id.button1), 1, this); 
rele[1] = new ReleController(findViewById(R.id.button2), 2, this); 
rele[2] = new ReleController(findViewById(R.id.button3), 3, this); 
rele[3] = new ReleController(findViewById(R.id.button4), 4, this); 

など、私のボタンレイアウトに見える:私はこのような何か実行する方法があれば把握しようとしています

<LinearLayout style="@style/CoreLayout"> 

    <ImageButton 
     android:id="@+id/button1" 
     style="@style/Button.Blue" 
     android:src="@mipmap/ic_arrow_left" /> 

    <ImageButton 
     android:id="@+id/button2" 
     style="@style/Button.Green" 
     android:src="@mipmap/ic_arrow_right"/> 
</LinearLayout> 

<LinearLayout style="@style/CoreLayout"> 

    <ImageButton 
     android:id="@+id/button3" 
     style="@style/Button.Yellow" 
     android:src="@mipmap/ic_arrow_up"/> 

    <ImageButton 
     android:id="@+id/button4" 
     style="@style/Button.Purple" 
     android:src="@mipmap/ic_arrow_down"/> 
</LinearLayout> 

:実物で

for(int i = 0; i < 4; i++) 
{ 
    rele[i] = new ReleController(findViewById(R.id.button[i+1]), i+1, this); 
} 

を、私は8を持っていますボタンがあるので、すべてのボタンにこれらの行をすべて書き込むのは本当に面倒です。

ボタンIDは、このような配列として宣言することができる場合、私は疑問に思って

android:id="@+id/button[1]" 
android:id="@+id/button[2]" 
android:id="@+id/button[3]" 
... 

は、すべてのあなたの答えをいただき、ありがとうございます。

+2

いいえ.....しかし、あなたは 'int [] = {R.id.1、R.id.2、R.id.N}' – Selvin

+1

を使用することができますか?http:// stackoverflow .com/questions/15642104/array-of-buttons-in-android [最も価値のある回答を確認] – RubioRic

答えて

2

アレイを使用してビューのIDを格納できます。

int[] buttonId = new int[] { R.id.button1, R.id.button2, R.id.button3, R.id.button4 } 

次に、このように配列を宣言してください。

+0

私が探していた機能がAndroidに実装されていない場合は、これが最適です。本当にありがとう。私には恥ずべき。私はこれを自分では考えていない。 –

+1

「これらのすべての行を書き込む」にはあまりにも迷惑な場合は、ButterKnifeを見てください。ビューを見つけてバインドするときは、多くの場合、入力の手間が省けます。 http://jakewharton.github.io/butterknife/ – babadaba

関連する問題