Tuesday, 17 September 2013

Declare many imvageviews in code

If you need declare many views in code without pasting monkey code here is the solution.
The key of solution is TypedArray object.

Let's say we have layout with N imageviews in our layout, each element has own id.

First we need make in res folder file where we will store elements ids in array, it can be arrays.xml
So we write example this:

<array name="avatars_icons">
        <item>@+id/img0</item>
        <item>@+id/img1</item>
        <item>@+id/img2</item>
        <item>@+id/img3</item>
        <item>@+id/img4</item>
        <item>@+id/img5</item>
        <item>@+id/img6</item>
        <item>@+id/img7</item>
        <item>@+id/img8</item>
        <item>@+id/img9</item>
        <item>@+id/img10</item>
        <item>@+id/img11</item>
        <item>@+id/img12</item>
        <item>@+id/img13</item>
        <item>@+id/img14</item>
    </array>

Then we need have array with theirs images

<array name="avatars_male">
        <item>@drawable/m0</item>
        <item>@drawable/m1</item>
        <item>@drawable/m2</item>
        <item>@drawable/m3</item>
        <item>@drawable/m4</item>
        <item>@drawable/m5</item>
        <item>@drawable/m6</item>
        <item>@drawable/m7</item>
        <item>@drawable/m8</item>
        <item>@drawable/m9</item>
        <item>@drawable/m10</item>
        <item>@drawable/m11</item>
        <item>@drawable/m12</item>
        <item>@drawable/m13</item>
        <item>@drawable/m14</item>
    </array>

And in code we do something like that

TypedArray avatarsImageViews = getResources().obtainTypedArray(R.array.avatars_icons);
TypedArray avatarsSex = getResources().obtainTypedArray(R.array.avatars_male);

 for (int i = 0; i < avatarsImageViews.length(); i++) {
            ImageView iv = (ImageView) findViewById(avatarsImageViews.getResourceId(i, 0));
            iv.setImageDrawable(avatarsSex.getDrawable(i));
            //...
            iv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //stuff                }
            });
        }