在listview中单击了错误的项目图像按钮

时间:2014-09-09 17:07:33

标签: android listview android-listview

我有一个包含项目的列表视图。每个项目都有一个图像按钮。单击图像按钮时,我想使用以下代码更改其图像。代码确实会更改单击的按钮,但它也会更改其他项目'未单击的图像。为什么会这样,以及如何解决?

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (view == null) {
            view = lInflater.inflate(R.layout.item, parent, false);
        }


        final ImageButton playButton = ((ImageButton) view.findViewById(R.id.play_pause));

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // In the log I get correct position of clicked item, but the image changes are wrong.
                Log.d(TAG, "Clicked row-" + view.getTag().toString());
                ((ImageButton) view.findViewById(R.id.play_pause)).setImageResource(R.drawable.button_pause);


            }
        });

        playButton.setTag(position);
        return view;
    }

1 个答案:

答案 0 :(得分:0)

在适配器的开头添加它

HashMap<Integer,Boolean> states = new HashMap<Integer, Boolean>();

在你的onClick中添加:

if(states.containsKey(position))
{
   states.put(position, !states.get(position));
   ((ImageButton) view.findViewById(R.id.play_pause)).setImageResource(states.get(position)?R.drawable.button_pause:R.drawable.button_play);
}
else
{
   states.put(position, true);
   ((ImageButton) view.findViewById(R.id.play_pause)).setImageResource(R.drawable.button_pause);
}

在您的返回视图之前添加以下内容:

if(states.containsKey(position) && states.get(position))
   ((ImageButton) view.findViewById(R.id.play_pause)).setImageResource(R.drawable.button_pause);
else
   ((ImageButton) view.findViewById(R.id.play_pause)).setImageResource(R.drawable.button_play);