I just want to create buttons programmatically in android that i do know. But the thing is creating the button with certain number in a row and it's completely dependents on orientation of the screen.
For instance, If the device in portrait mode I just need two button in a row and three or four in landscape (for mobile) and four or five (for tablets) with alignment.
Edited
I have tried below code and got something
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
pwidth = size.x;
lHeight = size.x;
pheight = size.y;
lWidth = size.y +16;
scrollView = new ScrollView(MainActivity.this);
scrollView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
gl = new GridLayout(MainActivity.this);
gl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
gl.setOrientation(GridLayout.HORIZONTAL);
int orientation = this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
//code for portrait mode
Toast.makeText(getApplicationContext(), "PORTRAIT", Toast.LENGTH_SHORT).show();
if ( pheight > pwidth) {
columnSize = pheight / pwidth;
gl.setColumnCount(columnSize + 1);
gl.setRowCount(columnSize + 1);
Log.i("PORTRAIT WIDTH", String.valueOf(pwidth));
Log.i("PORTRAIT HEIGHT", String.valueOf(pheight));
Log.i("PORTRAIT COLUMN SIZE ", String.valueOf(columnSize));
Log.i("PORTRAIT ROW SIZE ", String.valueOf(rowSize));
}/*else if(width>height){
}*/
} else {
//code for landscape mode
Toast.makeText(getApplicationContext(), "LANDSCAPE", Toast.LENGTH_SHORT).show();
if (lWidth < lHeight) {
columnSize = lWidth / 400;
gl.setColumnCount(columnSize + 1);
gl.setRowCount(columnSize);
Log.i("LANDSCAPE WIDTH", String.valueOf(lWidth));
Log.i("LANDSCAPE HEIGHT", String.valueOf(lHeight));
Log.i("LANDSCAPE COLUMN SIZE ", String.valueOf(columnSize));
Log.i("LANDSCAPE ROW SIZE ", String.valueOf(columnSize));
}
}
Log.i("ROW SIZE ", String.valueOf(columnSize));
button = new Button[9];
for (int i = 0; i < 9; i++) {
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = 200;
param.width = GridLayout.LayoutParams.WRAP_CONTENT;
param.rightMargin = 100;
param.topMargin = 100;
param.leftMargin = 100;
param.setGravity(Gravity.CENTER);
button[i] = new Button(MainActivity.this);
button[i].setLayoutParams(param);
button[i].setText("Button " + String.valueOf(i));
button[i].setTextSize(20);
button[i].setPadding(50, 50, 50, 50);
gl.addView(button[i]);
}
scrollView.addView(gl);
setContentView(scrollView);
for (item = 0; item < 9; item++) {
button[item].setOnClickListener(new View.OnClickListener() {
int pos = item;
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), pos + " Clicked",
Toast.LENGTH_SHORT).show();
}
});
}