我可以在Android中将android:id声明为数组吗?

时间:2016-08-17 08:41:54

标签: java android layout

我有这段代码。

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]"
...

感谢您的所有答案。

1 个答案:

答案 0 :(得分:2)

您可以使用数组来存储视图的ID。只需声明您的数组:

closing_day_id

然后迭代它。