I am trying to display a grid of buttons using gridLayout at runtime. I am trying to fit the gridLayout to fit the entire screen's width. I am able to do that for 3x3 and 5x5 button grid (using my nexus 4). But when I go for 7x7, I lose the last column of buttons i.e the last column of GridLayout. I seriously cant understand whats going wrong here.
Here's what I am doing.. I take the grid size from settings activity and this is the number of columns in GridLayout (numColumns). I use LayoutParams and get the width and height and set the buttons' width and height to (layoutWidth/numColumns) and (layoutHeight/numColumns). Please help me here guyz.. I have pasted the code below.
public class StartGameActivity extends ActionBarActivity {
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_game);
SharedPreferences sharedPref= PreferenceManager.getDefaultSharedPreferences(this);
int numColumns=Integer.parseInt(sharedPref.getString("Grid", "3").toString());
// create a RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
//LinearLayout linearLayout = new LinearLayout(this);
// define the RelativeLayout layout parameters.
//LinearLayout.LayoutParams linearLayoutparams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
DisplayMetrics metrics=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width=metrics.widthPixels;
int height=metrics.heightPixels;
RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(width,height);
RelativeLayout.LayoutParams relativeLayoutParams1 = new RelativeLayout.LayoutParams(width,height);
GridLayout gridLayout=new GridLayout(this);
GridLayout.LayoutParams gridLayoutParams = new GridLayout.LayoutParams();
gridLayoutParams.setGravity(Gravity.FILL_HORIZONTAL);
gridLayout.setColumnCount(numColumns);
gridLayout.setRowCount(numColumns);
gridLayout.setMinimumHeight(height);
gridLayout.setMinimumWidth(width);
for(int i=0;i<numColumns*numColumns;i++)
{
Button button=new Button(this);
button.setWidth(width/numColumns);
button.setHeight(width/numColumns);
button.setMinWidth(width/numColumns);
button.setMinHeight(width/numColumns);
button.setGravity(Gravity.FILL);
//buttonForEveryRow++;
//columIndex++;
gridLayout.addView(button);
}
relativeLayout.addView(gridLayout,relativeLayoutParams1);
setContentView(relativeLayout,relativeLayoutParams);
}
}