我试图在文本视图中一次随机显示一个项目。我可以用下面的代码显示所有这些。
final HashMap<String, String> map = new HashMap<String, String>();
NodeList nodes = doc.getElementsByTagName("item");
// for (int i = 0; i < nodes.getLength(); i++) {
// creating new HashMap
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
map.put(KEY_TITLE,parser.getValue(element, KEY_TITLE));
menuItems.add(map);
List<String> valuesList = new ArrayList<String>(map.values());
int randomIndex = new Random().nextInt(valuesList.size());
randomValue = valuesList.get(randomIndex);
Log.i("inside", randomValue);
}
Collections.shuffle(menuItems);
menuItems.add(map);
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("outide",map.get(KEY_TITLE));
myImage.setImageResource(imageArr[rgenerator.nextInt(imageArr.length)]);
}
});
}
}
任何人都可以告诉我随机显示数据的最简单方法是什么?
谢谢,
嗨,大家好,
这就是我想出的,它似乎按我想要的方式工作。
final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(responseBody);
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
// creating new HashMap
// for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_TITLE,parser.getValue(element, KEY_TITLE));
menuItems.add(map);
}
Collections.shuffle(menuItems);
Map<String, String> myValueMap = menuItems.get(0);
textView.setText(myValueMap.get(KEY_TITLE));
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collections.shuffle(menuItems);
Map<String, String> MapBtn = menuItems.get(0);
textView.setText(MapBtn.get(KEY_TITLE));
myImage.setImageResource(imageArr[rgenerator.nextInt(imageArr.length)]);
}
});
}
}