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

Then we need have array with theirs images

<array name="avatars_male">

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.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    //stuff                }