Android 如何生成随机切换按钮的ID,然后将该特定切换按钮设置为选中(True)
我有两个切换按钮,我希望能够随机选择其中一个按钮的id,并将check按钮设置为true。我尝试了这一点,但它不起作用,因为setChecked不适用于Int或String。任何帮助都将不胜感激Android 如何生成随机切换按钮的ID,然后将该特定切换按钮设置为选中(True),android,random,togglebutton,android-identifiers,Android,Random,Togglebutton,Android Identifiers,我有两个切换按钮,我希望能够随机选择其中一个按钮的id,并将check按钮设置为true。我尝试了这一点,但它不起作用,因为setChecked不适用于Int或String。任何帮助都将不胜感激 int[] buttonIds = new int[] {R.id.player1Button, R.id.player2Button}; Random rand = new Random(); int num = rand.nextInt(buttonIds.length); int buttonId
int[] buttonIds = new int[] {R.id.player1Button, R.id.player2Button};
Random rand = new Random();
int num = rand.nextInt(buttonIds.length);
int buttonId = buttonIds[num];
findViewById(buttonId).toString();
String randomButton = getString(buttonId);
randomButton.setChecked(true); /// THIS LINE OF CODE WILL NOT WORK
最后你有点困惑了。您选择随机
id
的代码没有问题。但是ToggleButton
是一个类。它不是字符串
。如果通过toString()
将其转换为字符串
,则它将不具有任何切换按钮
功能。相反,您希望findViewById
获取id,将其强制转换为ToggleButton
并调用该ToggleButton
上的setChecked
,请改用此行
((ToggleButton)findViewById(buttonId)).setChecked(true);
谢谢你,朋友,我已经按照你说的去做了。我将最后三行更改为:
findviewbyd(buttonId)代码>ToggleButton randomButton=(ToggleButton)findViewById(buttonId)代码>randomButton.setChecked(true)代码>但是,由于启动时已检查其中一个切换按钮,有时两个切换按钮最终都会被检查。是否有办法获取数组中剩余按钮的id,以便我可以将其设置为false,同时只有2个id—您选择的随机索引为0或1。这两个值中的另一个是另一个按钮的索引。是否有方法获取数组中剩余按钮的id,以便我可以将其设置为false。有时两个切换按钮都可以检查,因为启动时其中一个按钮已经为真。对于(int i=0;我非常感谢您。按预期工作