简体   繁体   English

如何在android中的数组中添加按钮

[英]how can I add buttons in array in android

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

Each button should have a unique ID and you can use findViewById(R.id.ButtonX) to get the buttons. 每个按钮应该具有唯一的ID,并且您可以使用findViewById(R.id.ButtonX)来获取按钮。 Say you have 5 buttons: 假设您有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);

Of course the IDs have to match those in the XML. 当然,这些ID必须与XML中的ID相匹配。 You could also use an ArrayList<Button> if you need to add or remove buttons from this array. 如果需要从该数组添加或删除按钮,也可以使用ArrayList<Button> Do note that adding or removing from the array will not add or remove them from the activity. 请注意,从阵列中添加或删除不会将其添加到活动中。

Create an activity. 创建一个活动。 In Eclipse there should be 2 lower tabs with one letting you graphically edit the layout. 在Eclipse中,应该有2个下部选项卡,其中一个选项卡允许您以图形方式编辑布局。 Then all you have to do is link the Java buttons with the xml buttons. 然后,您要做的就是将Java按钮与xml按钮链接起来。

You can try something like this. 您可以尝试这样。 Assuming bi,b2 b3 are the button names in the XML 假设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"));

I understood that: You want to create dynamic button(You create button in java code not xml). 我的理解是:您想创建动态按钮(您在Java代码中创建按钮而不是xml)。 Try that way: 尝试这种方式:

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM