Search code examples
javaandroidandroid-imageviewplaying-cards

Setting 13 cards on screen in Android


enter image description here>

Im displaying 13 cards dynamically by getting Resource as string and setting its margin in a layout but they are not setting up without overlapping. I tried a lot by changing margin but not working.

int counter=0;
     forloop 1 to 13
     int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
                        im = (ImageView) findViewById(resID);
                        Context context = im.getContext();
                        cardID = context.getResources().getIdentifier(resourceName, "drawable", context.getPackageName());
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(im.getLayoutParams());
                        lp.setMargins(counter*30,0,0,0);//left,right,top,bottom
                        im.setLayoutParams(lp);
                        im.setImageResource(cardID);
                        counter++;




![Screen shot of 13 Cards ][2]

Solution

  • The issue is once you run out of horizontal space, you need to create a new row and add cards to that until that row runs out of space, etc.

    A GridLayout would be better suited for what you're trying to accomplish. You could also use a GridView or TableLayout. It would be rather complicated to do this using a RelativeLayout since the child views need to be laid out in relation to each other, so you'd need to know exactly which view each child to the right of and which view it's below.

    See this tutorial for an example of how to add views to a GridLayout dynamically: http://android-er.blogspot.com/2014/09/insert-view-to-gridlayout-dynamically.html