Q:

How to add 3 buttons in each rows

I want to add 3 buttons in each row where as ROW created by dynamic way.  I tried below way but it shows one button each row. 
 LinearLayout ll_rootOBJ = findViewById(R.id.ll_root);
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout. VERTICAL);

        int total_items=13;
        for (int k=0; k<total_items; k++)
        {
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout. HORIZONTAL);
            ll.setTag(k);

            Button b = new Button(this);
            b.setTag(k);
            b.setText("Button " + k);
            ll.addView(b);
            mainLayout.addView(ll);
        }

        ll_rootOBJ.addView(mainLayout);

Any help will be useful.  Thanks. 

A:

One easy answer would be to just add 3 buttons in each iteration.  I case it's the last iteration and there are less buttons to add just add less: 
    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout. VERTICAL);

    int totalItems = 13;
    for (int k=0; k<totalItems; k+=3)
    {
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout. HORIZONTAL);
        layout.setTag(k/3);

        int numberOfButtonsInRow = (k + 3 < totalItems) ?  3 : totalItems % 3;

        for(int l = 0; l < numberOfButtonsInRow; l++)
        {
            Button b = new Button(this);
            b.setTag(k + l);
            b.setText("Button " + (k + l));
            layout.addView(b);
        }

        mainLayout.addView(layout);
    }

Also I would suggest to extract the contents of the inner loop to a separate function, although I left it here to make it brief.