Apps Custom Layout extending RelativeLayout


Hello, I've problem with extending this layout. I don't seem to be able to find any good tutorials on this. I've dynamic views that I need to place on screen in rows, after the row has been fulled (getWidth methods in if) it should place the next one below the one on the left in current row. Here's the code (I've only overloaded onLayout method):

protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        LayoutParams lp;
        ImageView bookmark, previousBookmark;
        int idOfViewToTheLeft = 0; // Id of a View that is farthest to the left
        final int count = getChildCount();
        for(int i = 0; i < count; i++) {
            bookmark = (ImageView) findViewById(i);
            lp = (LayoutParams) bookmark.getLayoutParams();
            if(i > 0) {
                previousBookmark = (ImageView) findViewById(i - 1);
                 if(this.getWidth() > (previousBookmark.getLeft() + previousBookmark.getWidth())) {
                     lp.addRule(RelativeLayout.RIGHT_OF, previousBookmark.getId());
                 } else {
                     lp.addRule(RelativeLayout.BELOW, idOfViewToTheLeft);
                     idOfViewToTheLeft = bookmark.getId();