Java 帮助:android中的8 X 10二维按钮阵列
我在android中动态创建按钮时遇到了一个问题。这就是我想做的- 我想创建8 x 10的按钮数组。因为在main.xml中声明80个按钮效率不高,所以我想在程序本身中这样做。最大的问题是像网格一样放置/对齐按钮。我可以创建按钮对象,但如何在程序中对齐它们Java 帮助:android中的8 X 10二维按钮阵列,java,android,user-interface,button,Java,Android,User Interface,Button,我在android中动态创建按钮时遇到了一个问题。这就是我想做的- 我想创建8 x 10的按钮数组。因为在main.xml中声明80个按钮效率不高,所以我想在程序本身中这样做。最大的问题是像网格一样放置/对齐按钮。我可以创建按钮对象,但如何在程序中对齐它们 Button b = new Button(this); b.setId(i); b.setText("Button " + i); 像这样- 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 . . .
Button b = new Button(this);
b.setId(i);
b.setText("Button " + i);
像这样-
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
.
.
.
10 10 10 10 10 10 10 10 10 10
如果您能“以编程方式”完成此操作,我们将不胜感激。您需要一个容器将它们全部放入:
<LinearLayout
android:id="@+id/llContainer"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
然后我将它们添加为10个单独的“行”:
LinearLayout container = (LinearLayout) findViewById(R.id.llContainer);
for(int i = 0; i < 10; i++) {
LinearLayout row = new LinearLayout(this, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
container.addView(row);
for(int x = 0; x < 8; x++) {
Button btn = new Button(this, new LayouParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setText(i + ':' + x);
row.addView(btn);
}
}
LinearLayout container=(LinearLayout)findViewById(R.id.llContainer);
对于(int i=0;i<10;i++){
LinearLayout行=新的LinearLayout(此,新的LayoutParams(LayoutParams.FILL\u父级,LayoutParams.WRAP\u内容));
container.addView(行);
对于(int x=0;x<8;x++){
Button btn=新按钮(这是新的LayouParams(LayoutParams.WRAP_内容,LayoutParams.WRAP_内容));
btn.setText(i+':'+x);
行。添加视图(btn);
}
}
Wow!你使用的是什么设备,它的屏幕足够大,可以显示80个可点击的按钮?@Matt Lacey:软键盘大约有10-11个键宽,这取决于布局。OP想要适合8,所以相比之下这听起来不太合理。10个按钮的高度应该更容易。不过,屏幕上80个按钮的想法仍然给我敲响了可用性和设计的警钟。