如何通过循环数组设置button的id?
2013-02-20 10:47
218 查看
原问题来自于CSDN问答频道,更多解决方案请查看:http://ask.csdn.net/questions/1415
原问题描述:
通过循环设置5个button的id,每次都随机分配。
随机分配没有问题。
在使用两个方法,随机设置button的id以及设置文本的时候出现错误。
弄得很混乱不知道问题出在哪里了?
解决方案:
我认为你的循环中
可以用xml预设button:
然后在后面的代码中,随机文本:
原问题描述:
通过循环设置5个button的id,每次都随机分配。
随机分配没有问题。
在使用两个方法,随机设置button的id以及设置文本的时候出现错误。
弄得很混乱不知道问题出在哪里了?
Button b1, b2, b3, b4, b5; Button[] buttons = { b1, b2, b3, b4, b5 }; public void shuffleButtons() { Integer[] Id = { R.id.bChoice1, R.id.bChoice2, R.id.bChoice3, R.id.bChoice4, R.id.bChoice5 }; ArrayList<Integer> buttonId = new ArrayList<Integer>(Arrays.asList(Id)); Collections.shuffle(buttonId); for (int x = 0; x < 5; x++) { for (Button b : buttons) { b = (Button) findViewById(buttonId.get(x)); } } }
public void setButtonTxt() { for (Button b : buttons) { for (int x = 0; x <= buttons.length; x++) { b.setText(textList.get(x)); } } }
解决方案:
我认为你的循环中
x <= buttons.length应该是
x < buttons.length,但是你好像要将5个button设置给textList.get(5)
可以用xml预设button:
<Button android:id="@+id/bChoice1" ... /> <!-- etc --> <Button android:id="@+id/bChoice5" ... />
然后在后面的代码中,随机文本:
Button b1 = (Button)findViewById(R.id.bChoice1); Button b2 = (Button)findViewById(R.id.bChoice2); Button b3 = (Button)findViewById(R.id.bChoice3); Button b4 = (Button)findViewById(R.id.bChoice4); Button b5 = (Button)findViewById(R.id.bChoice5); // assuming textList is an ArrayList of text items // the next two lines will randomize your textList order // so you don't need to do it yourself and much less // error-prone long seed = System.nanoTime(); Collections.shuffle(textList, new Random(seed)); b1.setText(textList.get(0)); b2.setText(textList.get(1)); b3.setText(textList.get(2)); b4.setText(textList.get(3)); b5.setText(textList.get(4));
相关文章推荐
- 如何通过一次循环打印出三维数组的所有值
- 解决如何通过循环来使用数据库的值设置jsp的select标签的option值
- Flex中如何通过selectedButtonTextStyleName样式,设置ToggleButtonBar选中按钮文本颜色
- 通过 ID 数组设置子窗口的状态
- 原创:如何实现在Excel通过循环语句设置指定行的格式
- 【Win7中如何通过修改注册表将IE设置为默认浏览器】
- MSIL 教程(二):数组、分支、循环、使用不安全代码和如何调用Win32 API
- Flex中如何通过设置backgroundAlpha风格来设定VideoDisplay控件的背景透明度(background alpha)的例子
- Flex中如何通过设置fontFamily样式在NumericStepper控件中使用嵌入字体的例子
- C语言把内存的文件保存到硬盘时如何把文件名由用户通过屏幕自己设置,并且保存到指定的路径
- 如何使对象可以像数组一样进行foreach循环?
- CListCtrl虚拟列表如何通过代码设置选中某条记录
- 如何通过jquery异步传数组array数据到后台
- Flex Gumbo中如何通过textAlpha样式,设置TextGraphic透明度
- Flex中如何遍历TabBar控件的各个Tab,并且通过labelPlacement属性设置标签位置
- 如何通过Button获取UITableViewCell
- java里如何实现循环打印出字符或字符数组里的内容
- lua如何设置只读全局变量——通过元方法与环境
- 实例讲解:aiCache如何通过header-driven设置缓存失效