这是演示代码,当我在填充函数中添加onClickListener时,它不起作用,并且如果我设置任何其他属性(如背景色),则效果很好。

private void fillHolder(FriendsHolder holder, final Friend friend) {
        if (friend == null)
            return;
        Iterator<Button> iViews = holder.interests.iterator();
        Iterator<String> iInterests = friend.getInterests().iterator();
        while (iViews.hasNext() && iInterests.hasNext()) {
            iViews.next().setText(iInterests.next());
        }
        Iterator<Button> iViewss = holder.interests.iterator();
        while (iViewss.hasNext()) {
            iViewss.next().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
                }
            });
        }
        holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
        holder.nickName.setText(friend.getNickname());

    }
}

最佳答案

您正在遍历iViewss(最后是双S),并将侦听器设置为iViews(最后是单S)。

这不是同一对象。

iViews.next().setOnClickListener()将抛出NoSuchElementException,因为没有下一个元素。

像这样更改代码:

private void fillHolder(FriendsHolder holder, final Friend friend) {
        if (friend == null)
            return;
        Iterator<Button> iViews = holder.interests.iterator();
        Iterator<String> iInterests = friend.getInterests().iterator();
        while (iViews.hasNext() && iInterests.hasNext()) {
            iViews.next().setText(iInterests.next());
        }
        while (iViews.hasNext()) {
            iViews.next().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
                }
            });
        }
        holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
        holder.nickName.setText(friend.getNickname());

 }


编辑:

您还可以组合两个while循环(如cricket_007建议):

private void fillHolder(FriendsHolder holder, final Friend friend) {

            if (friend == null)
                return;

            Iterator<Button> iViews = holder.interests.iterator();
            Iterator<String> iInterests = friend.getInterests().iterator();

            while (iViews.hasNext()) {

                Button button = iViews.next();

                if (iInterests.hasNext()) {
                    button.setText(iInterests.next());
                }

                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
            holder.nickName.setText(friend.getNickname());

     }

10-01 20:36