我使用此功能创建了几个按钮:
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);
}
}
当我在NavigationDrawer中单击某些内容时调用了这个参数:numbers_of_buttons是通过在sqlite数据库中完成的某些查询来检索的。
我唯一的问题是,如果numbers_of_buttons是&gt; 7即(25)我只能看到其中的7个。 这是因为我的scrren宽度是720像素(Nexus7)。
那我该怎么办呢? 我的想法是 - 计算屏幕的宽度
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
System.out.println("DisplayWidth -> " + metrics.widthPixels);
无法找到第二种伪代码的方法。
编辑 - 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]);
}