如何更新ArrayAdapter的getView方法中的视图?

时间:2011-11-25 10:44:39

标签: android listview android-arrayadapter

我有以下问题。我有ListView我正在使用扩展ArrayAdapter类的自定义适配器。在每行中都有一个跟随Button,当我点击它时我需要改变它的风格。

到目前为止,我有:

public View getView(final int position, View convertView, ViewGroup parent) {
        View vi = convertView;

        if (convertView == null) {  
            vi = inflater.inflate(R.layout.people_item, null);

            mViewHolder = new ViewHolder();              
            mViewHolder.follow = (Button) vi.findViewById(R.id.people_item_btn_follow);
            mViewHolder.name = (TextView)....
            vi.setTag(mViewHolder);         
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        mViewHolder.follow.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Changing the style of the button
                if(mData[position].getFollow().equals("0")) {
                    mViewHolder.follow.setBackgroundDrawable(mCtx.getResources().getDrawable(R.drawable.unfollow_button_border));
                    mViewHolder.follow.setText(mCtx.getString(R.string.unfollow));
                } else {
                    mViewHolder.follow.setBackgroundDrawable(mCtx.getResources().getDrawable(R.drawable.follow_button_border));
                    mViewHolder.follow.setText(mCtx.getString(R.string.follow));
                }

                mSharedAsyncTasks.getFollowerTask().execute(mData[position].getId());
            }
        });

        if(mData[position] != null) {
            // Setting data
        }

        return vi;
    }

private static class ViewHolder {
    TextView fullName;
    Button follow;
}

问题是,当点击任何行的按钮时,新样式将应用于另一行的按钮(尽管以下效果将应用于右行)。

我知道这与行被回收/重复使用的事实有关。

但如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

不确定要执行以下操作。

 public void onClick(View v) {
      mViewHolder.follow.setBackgroundDrawable(mCtx.getResources().getDrawable(R.drawable.unfollow_button_border));
      ...
 }

具体来说,我认为这个问题是你的引用mViewHolder看起来像它的悬挂,并在你滚动时可以指向任何按钮。这是一个范围问题,您应该能够解决以下问题。在onClick(View v)v中我相信是你点击过的按钮。

相反,您应该可以执行以下操作

 public void onClick(View v) {
      ((Button)v).setBackgroundDrawable(mCtx.getResources().getDrawable(R.drawable.unfollow_button_border));
      ...
 }
相关问题