1

我是编程新手,但有一些空闲时间,刚买了一个新的安卓平板电脑,所以我想是时候学习了。我玩一个棋盘游戏,它有很多套牌,你可以在整个游戏过程中从中抽取,我决定最好有一个显示 21 套套牌的应用程序,然后你点击其中一个,它会随机显示其中一个套牌中的一张牌. 你阅读卡片,采取行动,点击卡片,它就会消失。

因此,我的布局包含所有 21 个卡座 (7x3),每个卡座都有一个单独的按钮。因此,我在 1 个屏幕上有 21 个按钮。根据我一直在关注的教程,我需要在 .java 文件button1 = (Button) findViewById(android.R.id.button1)上声明按钮。但它只能选择声明 3 个按钮,然后我得到厄运的小红色 x。

我该如何声明所有 21 个按钮?或者我不需要声明这些按钮?

任何帮助都会很棒!(可能还需要帮助找到一种方法来随机化“绘制”功能,所以再次见到我不要感到惊讶)

4

4 回答 4

0

您确实需要定义每个按钮。使用以下:

Button button1 = (Button)findViewById(R.id.idofbutton1);
Button button2 = (Button)findViewById(R.id.idofbutton2);
Button button3 = (Button)findViewById(R.id.idofbutton3);
Button button4 = (Button)findViewById(R.id.idofbutton4);

以此类推

于 2012-04-09T00:28:20.173 回答
0

如果您在 XML(main.xml 或类似的东西)中布置每个按钮,那么是的,如果您希望它们做任何事情,您必须按照您所说的声明按钮。

Button button1 = (Button) findViewById(R.id.button1);

通过以这种方式输入,我假设您没有将代码中较高的按钮声明为类范围的字段。另外,您是否运行了 setContentView(R.layout.main); 方法?

所以让我们明确一点:除非你输入 Button b1; 按钮 b2; 按钮 b3 就在你的类线下方 (public class YourClassName() {,每次你尝试实例化一个按钮时,你必须说 Button b1 = (Button) findViewById(R.id.button1);。如果你确实做了类-宽字段(在类行的正下方)然后您可以拥有像您在原始问题中显示的代码,它只是 button1 = (Button) findViewById(R.id.button1)。这种区别有意义吗?

于 2012-04-09T00:28:43.730 回答
0

此外,如果您想在循环中执行此操作,您也可以这样做。可能会让事情变得容易一些。这是一个链接:https ://stackoverflow.com/a/8687807/1231943

于 2012-04-09T00:33:10.267 回答
0

任何时候你声明一个 Button (它是一个对象):

Button button1 = (Button)findViewById(R.id.idofbutton1);
Button button2 = (Button)findViewById(R.id.idofbutton2);

确保将“id”添加到 XML 布局中:

 <Button
   android:id="@+id/idofbutton1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Button1"
   android:textSize="20px" >
</Button>

<Button
   android:id="@+id/idofbutton2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Button2"
   android:textSize="20px" >
</Button>
于 2012-04-09T00:52:28.290 回答