通过单击同一行的另一个元素更改ListView元素

时间:2015-08-28 05:17:01

标签: android listview android-listview baseadapter getview

我有一个ListView和一个带有两个元素的简单适配器类。我只想通过克服另一个元素来改变一个元素,但每当我向下或向上滚动时,改变就会消失。我研究了这两个链接

Why do items disappear when I scroll the listView?

Clickable element in custom ListView row

我知道listView具有回收功能,这就是原因,但是我想要一个简单的解决方案而不刷新整个列表,当我在多行上更改时,它应该在getView调用之后我的意思是在向上或向下滚动之后。 这是我的适配器类代码

public class Pha extends BaseAdapter {

private List<PhaMessages> pList = new ArrayList<PhaMessages>();
private Activity context;
ViewHolder viewHolder = null;

int fCounted = 0;


public Pha(Activity cont, ArrayList<PhaMessages> posts){
    this.context = cont;
    this.pList = posts;
    Log.d("pha","called constructor..");
}

static class ViewHolder {
    protected TextView fCount;
    protected ImageView fIcon;
}

@Override
public int getCount() {
    return pList.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {


    if (convertView == null) {

        LayoutInflater inflator = context.getLayoutInflater();
        convertView = inflator.inflate(R.layout.pha_list_row, null);
        viewHolder = new ViewHolder();


        viewHolder.fIcon = (ImageView)convertView.findViewById(R.id.f_counter_img);
        viewHolder.fCount = (TextView)convertView.findViewById(R.id.f_plus);


        convertView.setTag(viewHolder);

    } else {
        viewHolder = (ViewHolder) convertView.getTag();

    }

    final ViewHolder hold = viewHolder;

        viewHolder.fCount.setText("" + pList.get(position).NumFrnd);



    viewHolder.fIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


                if(!t){
                    fCounted++;


                    hold.fCount.setText(""+fCounted);

        // by doing this at list I can see an immediate change that the number is changing
        //
        //but is i do viewHolder.fCount.setText(""+fCounted); I see another row changing

                }else {
                    Toast.makeText(context,"You have already clcik this.",Toast.LENGTH_SHORT).show();
                }


        }
    });

    return convertView;
}

}
提前谢谢。

1 个答案:

答案 0 :(得分:0)

当您在集合中增加fCounted值增量时,即pList

getview方法中将位置作为fCount组件

中的标记
viewHolder.fIcon.setTag(position);  // this is to get exact position for which we will change/increment value

现在使用fIcon的OnClickListener方法

   viewHolder.fIcon.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {


                if(!t){
                    fCounted++;

                  hold.fCount.setText(""+fCounted);
                  int position = (int)v.getTag();
                  int oldValue = pList.get(position).NumFrnd;
                  pList.get(position).NumFrnd = ++oldValue;
          }

}
};