Im creating several buttons by using this function:
private void setlayout(Integer numbers_of_buttons){
// creating LinearLayout
LinearLayout linLayout = new LinearLayout(this);
// creating LayoutParams
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
// set LinearLayout as a root element of the screen
setContentView(linLayout, linLayoutParam);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button[] butArray = new Button[numbers_of_buttons];
for (int i = 0; i < numbers_of_buttons; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText("i ... " + i);
butArray[i].setId(i); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (i != 0) {
Btnparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, butArray[i -1].getId());
}
butArray[i].setOnClickListener(listener);
linLayout.addView(butArray[i], Btnparams);
}
}
Which is called when I click something in my NavigationDrawer and the parameter: numbers_of_buttons is retrieved by some query done in the sqlite database.
My only issues is that if numbers_of_buttons is > 7 i.e. (25) i can see only 7 of them. This is because my scrren width is 720pixel (Nexus7).
So how am I suppose to handle this ? My idea is - calculate the widthness of the screen
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
System.out.println("DisplayWidth -> " + metrics.widthPixels);
- if getLeft() of last button create is > screenwidth than go to next row.
Can't find a way to do the second pseudocode.
EDIT - 1
private void setlayout(Integer numbers_of_buttons){
FlowLayout flowLayout = new FlowLayout(this);
setContentView(flowLayout);
Button[] butArray = new Button[numbers_of_buttons];
for (int i = 0; i < numbers_of_buttons; i++)
{
butArray[i] = new Button(this);
butArray[i].setText("i ... " + i);
butArray[i].setId(i);
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
butArray[i].setOnClickListener(listener);
flowLayout.addView(butArray[i]);
}