It's hackish but it works?The Main LinearLayout in the xml is in vertical orientation.
So it checks the total width of all the buttons you've generated against screen width and if it's more than or equal it will create a new linearlayout with horizontal orientation and continue putting buttons in.
This just takes in number of buttons you want to create.
private void generateButton(int noOfButton){
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
totalButtonWidth = 0;
while(noOfButton!= 0){
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int phoneWidth = metrics.widthPixels;
button = new Button(this);
button.setLayoutParams(new LinearLayout.LayoutParams(244,200));
totalButtonWidth += 244;
Log.i(TAG,"totalWidth"+totalButtonWidth);
if(totalButtonWidth>=phoneWidth){
totalButtonWidth = 244;
linearLayoutMain.addView(linearLayout);
linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
}
linearLayout.addView(button);
noOfButton--;
}
linearLayoutMain.addView(linearLayout);
}