如何仅以编程方式在android中添加动态网格布局?
Posted
技术标签:
【中文标题】如何仅以编程方式在android中添加动态网格布局?【英文标题】:how to add dynamic grid layout in android by only programmatically? 【发布时间】:2017-12-10 06:21:52 【问题描述】:我想只使用 java 代码在我的 android 应用程序中动态添加布局,而不是使用 XML 代码。请帮我解决这个问题。提前谢谢。
【问题讨论】:
你能说得更具体些吗?到目前为止,您取得了什么成就? 你可以使用recyclerview,使用recyclerView的StaggeredGridLayoutManager来达到想要的效果。更多信息请参考链接:inducesmile.com/android/… 【参考方案1】:使用这段代码我已经做到了:
public void makeSeat()
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(3,3,3,3);
GridLayout gl = (GridLayout) findViewById(R.id.grid_main);
int column = 4;
int row = 5;
int i_total = 4*5;
int i_busSeatNo = 1;
gl.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
gl.setColumnCount(column);
gl.setRowCount(row + 1);
CheckBox btn;
for(int i =0, c = 0, r = 1; i < i_total; i++, c++)
if(c == column)
c = 0;
r++;
i_busSeatNo++;
if (r == c+1 )
i_busSeatNo = r;
btn = new CheckBox(this);
btn.setGravity(Gravity.CENTER);
btn.setBackgroundResource(R.drawable.chbox);
btn.setButtonDrawable(R.drawable.chbox);
btn.setHeight(val_seat);
btn.setWidth(val_seat);
btn.setText(""+i_busSeatNo); //(r+" "+c); //r+" "+c
int cnt = Integer.parseInt(r+""+c);
btn.setId(cnt);
final CheckBox finalBtn = btn;
btn.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Toast.makeText(DynamicBus.this,
"id: " + finalBtn.getId() + "\nNo: " + finalBtn.getText(),
Toast.LENGTH_SHORT).show();
);
if(c != column-1)
i_busSeatNo = i_busSeatNo+5;
gl.addView(btn, i);
GridLayout.LayoutParams param =new GridLayout.LayoutParams();
param.height = val_seat;
param.width = val_seat;
param.rightMargin = 7;
param.topMargin = 7;
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(c);
if (r==1)
param.rowSpec = GridLayout.spec(r,1);
btn.setLayoutParams (param);
输出:
我得到了什么:
https://i.stack.imgur.com/FqynC.png
我想要什么:
https://i.stack.imgur.com/QZCTI.png
【讨论】:
以上是关于如何仅以编程方式在android中添加动态网格布局?的主要内容,如果未能解决你的问题,请参考以下文章
Android:当布局已经包含按钮时,如何以编程方式覆盖整个布局?