【问题标题】:for an onClick function, how do I make it so that it gives me the next element in a list from current?对于 onClick 函数,如何制作它以便它为我提供当前列表中的下一个元素?
【发布时间】:2016-01-16 12:36:45
【问题描述】:

我正在 android studio 中为 android 开发一个 anagram 应用程序。我目前正在研究一种“跳过”方法来跳过列表中的当前单词并向我显示列表中的下一个单词。我需要一个按钮来执行此操作,但是每次单击它时,它都会将我带到最后一个元素。我猜每次调用该方法时,它只是从头到尾迭代并向我显示最后一个元素。

    public void skip (View v){
        TextView scrambleView = (TextView) findViewById(R.id.scrambleView);

        for (ListIterator<String> i = wordBank.listIterator(); i.hasNext();) {
            String item = i.next();
            scrambleView.setText(scramble(r, item));
    }
}

【问题讨论】:

  • 如果要获取下一个值,为什么要使用for循环?

标签: java android android-studio skip anagram


【解决方案1】:

不要使用for循环(我不太明白你为什么要使用它),只需从列表中获取下一个值:

public void skip (View v){

    TextView scrambleView = (TextView) findViewById(R.id.scrambleView);
    String item = wordBank.get(next_index);
    scrambleView.setText(scramble(r, item));

}

如果不知道索引,可以使用如下方法:

public String getNext(String yourWord) {
       int idx = wordBank.indexOf(yourWord);
       if (idx < 0 || idx+1 == myList.size())
           return "";

       return wordBank.get(idx + 1);
}

【讨论】:

    【解决方案2】:

    您首先不需要使用循环。你可以使用:

    public void skip (View v){
        TextView scrambleView = (TextView) findViewById(R.id.scrambleView);
        String item=wordBank.listIterator().next();
        scrambleView.setText(scramble(r, item));
    }
    

    【讨论】:

    • 感谢您的回复,我不太确定为什么我首先使用循环(脑放屁之类的),但是使用此代码它将显示列表中的下一项,但是再次单击时,它会显示相同的单词(应该转到列表中的下一个单词)。另外我要注意的是,当游戏开始时,列表的第一个单词(索引 0)是默认显示的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2018-04-29
    相关资源
    最近更新 更多