2

我是 android 的新用户,制作幻灯片益智游戏并使用 eclipse。我在 xml 文件中制作了按钮。在 java 文件中,我制作了一个按钮类型的数组。现在我的问题是如何将我的按钮添加到我在 xml 中制作的数组中表格布局中的文件...

4

4 回答 4

3

每个按钮都应该有一个唯一的 ID,您可以使用它findViewById(R.id.ButtonX)来获取按钮。假设您有 5 个按钮:

Button[] buttons = new Button[5];
buttons[0] = (Button)findViewById(R.id.Button0);
buttons[1] = (Button)findViewById(R.id.Button1);
buttons[2] = (Button)findViewById(R.id.Button2);
buttons[3] = (Button)findViewById(R.id.Button3);
buttons[4] = (Button)findViewById(R.id.Button4);

当然,ID 必须与 XML 中的 ID 相匹配。ArrayList<Button>如果需要从该数组中添加或删除按钮,也可以使用。请注意,从数组中添加或删除不会在活动中添加或删除它们。

于 2012-11-06T14:59:59.407 回答
1

你可以尝试这样的事情。假设 bi,b2 b3 是 XML 中的按钮名称

ArrayList<Button> bl = new ArrayList<Button>();
bl.add(new Button("b1"));
bl.add(new Button("b2"));
bl.add(new Button("b3"));

于 2012-11-06T15:05:21.527 回答
1

创建一个活动。在 Eclipse 中应该有 2 个较低的选项卡,其中一个可以让您以图形方式编辑布局。然后您所要做的就是将 Java 按钮与 xml 按钮链接起来。

于 2012-11-06T14:58:51.800 回答
1

我明白:你想创建动态按钮(你在java代码而不是xml中创建按钮)。试试这样:

    Button btn1 = new Button(this);
    Button btn2 = new Button(this);
    Button btn3 = new Button(this);

    //your table name : tbl
    //you must create TableRow and add button to anyone row.And add row to table
    TableRow row1 = new TableRow(this);
    TableRow row2 = new TableRow(this);

    row1.addView(btn1);

    row2.addView(btn2);
    row2.addView(btn3);

    tbl.addView(row1);
    tbl.addView(row2);
于 2012-11-06T15:08:22.253 回答