我正在尝试制作一个随机按钮,它会随机重新排序GridView中的TextView项目(简单字母)。我试图简单地复制元素列表Collections.shuffle()
,然后循环遍历GridView中的实际元素并将新特征应用于它们。但是,当我这样做时,在两次或三次按下后,所有的字母和特征都是相同的。
@Override
public void onCreate(Bundle savedInstanceState) {
private static final String[] LETTERSET = generateLetterset.main();
gridView = (GridView) findViewById(R.id.lettersGrid);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.letter_text_view_item, LETTERSET);
gridView.setAdapter(adapter);
public void Shuffle(View v) {
gridView = (GridView) findViewById(R.id.lettersGrid);
List<TextView>letterList = new ArrayList<>();
for (int i = 0; i < gridView.getChildCount(); i++) {
TextView letter = (TextView) gridView.getChildAt(i);
letterList.add(letter);
}
Collections.shuffle(letterList);
for (int i = 0; i < gridView.getChildCount(); i++) {
TextView currentLetter = (TextView) gridView.getChildAt(i);
TextView newLetter = letterList.get(i);
String txt = newLetter.getText().toString();
boolean selected = newLetter.isClickable();
int color = newLetter.getCurrentTextColor();
currentLetter.setText(txt);
currentLetter.setClickable(selected);
currentLetter.setTextColor(color);
}
}
答案 0 :(得分:0)
尝试以下代码。 *在oncreate之外声明适配器对象
private static final String[] LETTERSET = generateLetterset.main();
public ArrayAdapter<String> adapter;
private ArrayList<String> stringList;
public void onCreate(Bundle savedInstanceState) {
gridView = (GridView) findViewById(R.id.lettersGrid);
stringList = new ArrayList<String>(Arrays.asList(LETTERSET ));
adapter = new ArrayAdapter<String>(this,R.layout.letter_text_view_item, stringList );
gridView.setAdapter(adapter);
}
并更新Shuffle功能如下
public void Shuffle(View v) {
Collections.shuffle(stringList);
adapter.notifyDataSetChanged();
}