我正在制作一个 ListView ,其中包含(除其他外)2 个 ImageView 和一个 TextView。两个ImageView是加号和减号图标,当它们被按下时,需要更新TextView内部的数字。他们还需要触发代码来更新 ListView 下面的 TextView 的总和。
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.basket_item, null);
holder.plus = (ImageView) convertView.findViewById(R.id.count_add);
holder.minus = (ImageView) convertView.findViewById(R.id.count_minus);
holder.counter = (TextView) convertView.findViewById(R.id.text_counter);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.id = position;
holder.counter.setId(position);
holder.counter.setText(count[position]);
holder.plus.setId(position);
holder.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = v.getId();
if (count[id] < 999) {
count[id]++;
totalcount++;
}
}
});
holder.minus.setId(position);
holder.minus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int id = v.getId();
if (count[id] > 1) {
count[id]--;
totalCount--;
}
}
});
return convertView;
}
}
class ViewHolder {
ImageView plus;
ImageView minus;
TextView counter;
int id;
}
我相信,要更新 TextView 中的计数器,我需要以某种方式将我的“持有者”放入 OnClickListner 中,但是,因为它没有声明为最终的,所以我不能。
有没有更简单的方法来做到这一点,或者我在这里错过了一个技巧?
最佳答案
尝试实现再次调用getView的notifyDataSetChanged()。之后使 textView 无效。但我不完全确定是否需要在这里调用 invalidate() 。
public void onClick(View v) {
int id = v.getId();
if (count[id] > 1) {
count[id]--;
totalCount--;
notifyDataSetChanged();
holder.counter.invalidate();
}
}
});
关于java - Android OnClickListener 更新同一 ListView 行中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20332538/