gpt4 book ai didi

java - 在android上动态添加按钮作为行和列?

转载 作者:行者123 更新时间:2023-12-01 14:40:50 26 4
gpt4 key购买 nike

public class MainActivity extends Activity {
int i,j;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
LinearLayout layout2 = new LinearLayout(this);
layout2.setOrientation(LinearLayout.HORIZONTAL);
layout2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
LinearLayout layout1 = new LinearLayout(this);
layout1.setOrientation(LinearLayout.VERTICAL);
layout1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

for(j=0;j<5;j++){
Button myButton = new Button(this);
myButton.setText(""+j);
myButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myButton.setTextSize(20);
layout.addView(myButton);
}
layout1.addView(layout);
for(j=5;j<10;j++){
Button myButton = new Button(this);
myButton.setText(""+j);
myButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myButton.setTextSize(20);
layout2.addView(myButton);
}
layout1.addView(layout2);

setContentView(layout1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

以上是我的代码。我能够动态创建两行 5 列的按钮。但在这里我必须手动创建行布局(layout,layout2)。我想我会定义一个线性布局数组。但是当我尝试指定 setOrientation 和 setLayoutParams 时,程序崩溃了。我试过了

layout3[0].setOrientation(LinearLayout.HORIZONTAL);

但是程序崩溃了。

最佳答案

其实很简单

您需要指定

layout3[i] = new LinearLayout(this);
layout3[i].setOrientation(LinearLayout.HORIZONTAL);
layout3[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

然后就可以了。

关于java - 在android上动态添加按钮作为行和列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com