3

I have this code.

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

And my button layout looks like:

<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>

I am trying to figure if there is a way to do something like this:

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

In real, I have 8 buttons, so it is really annoying to write all these lines for all buttons.

I am wondering if the button IDs can be declared as array like this:

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

Thank you for all your answers.

2
  • 2
    no ..... but you can use int[] = {R.id.1, R.id.2, R.id.N} Commented Aug 17, 2016 at 8:45
  • 1
    Maybe you mean something like this stackoverflow.com/questions/15642104/… [Check the most valued answer] Commented Aug 17, 2016 at 8:48

1 Answer 1

7

You can use an array to store the id of views. Just declare your array like this:

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

Then iterate through it.

Sign up to request clarification or add additional context in comments.

2 Comments

If the functionality what I was looking for is not implemented in Android, this is the best option. Thank you really much. Shame on me I have not figured this myself :).
If it's too annoying to "write all these lines" have a look at ButterKnife. It often saves alot of typing when finding and binding views. jakewharton.github.io/butterknife

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.