【问题标题】:How to shuffle TextView elements within GridView?如何在 GridView 中随机播放 TextView 元素?
【发布时间】:2015-12-18 01:11:16
【问题描述】:

我正在尝试制作一个随机播放按钮,该按钮将随机重新排序我的 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);
        }
    }

【问题讨论】:

  • 与任何其他 AdapterView 一样...洗牌适配器的底层数据并通知适配器视图有关更改
  • 第一次for循环后,彻底删除所有的GridView元素,然后打乱列表再添加到GridView,可以试试。
  • Selvin,你能详细说明一下实现吗?谢谢

标签: java android gridview android-studio


【解决方案1】:

试试下面的代码。 * 在 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);
    }

并更新随机播放功能如下

public void Shuffle(View v) { 
    Collections.shuffle(stringList); 
    adapter.notifyDataSetChanged();
}

【讨论】:

  • 在我当前的代码中我实际使用它,我的问题是在哪里以及如何使用 GridView 来实现它
  • 是的,奇怪的是每次随机播放列表都会变得更加同质。例如,如果列表是 [a, b, c, d, e, f, g] 它将变成类似 [f, c, c, a, c, a, b] 然后 [a, b, c, c, c, c ],然后 [c, c, c, c, c, c, c, ]
  • 你能把最初设置数据的代码发布到你的gridview
  • 更新了我的答案。我希望这能解决你的问题。如果数据已更改,notifyDataSetChanged() 会刷新视图。
  • 这感觉很接近,但它不起作用。我认为 notifyDataSetChanged() 不起作用,因为 letterList() 不是适配器的一部分,只是创建了一个新的 List 来反映适配器中的数据
猜你喜欢
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
相关资源
最近更新 更多