在同一个activity中,有时listView中的item的数据的改变会影响listView外的数据,之前总是傻傻的使用广播通知界面更改。最近看了下接口的使用。直接贴代码。
activity中代码
privateTextViewtv_result;
privateListViewlv_goods;
privateListlist=newArrayList<>();
privateContextcontext;
privateGoodsAdapteradapter;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_goods= (ListView) findViewById(R.id.lv_goods);
tv_result= (TextView) findViewById(R.id.tv_result);
context=this;
list.add(newGoodsBean("10","0"));
list.add(newGoodsBean("8","0"));
list.add(newGoodsBean("7","0"));
list.add(newGoodsBean("3","0"));
adapter=newGoodsAdapter(context,list);
adapter.setIOnPriceListener(newGoodsAdapter.IOnPriceListener() {
@Override
public voidupdatePrice(Integer price) {
tv_result.setText(price+"");
}
});
lv_goods.setAdapter(adapter);
}
adapter中代码
privateContextmContext;
privateListmlist;
private intmoney=0;
publicIOnPriceListenerlistener;
public voidsetIOnPriceListener(IOnPriceListener listener) {
this.listener= listener;
}
public interfaceIOnPriceListener {
voidupdatePrice(Integer price);
}
publicGoodsAdapter(Context context,List list) {
mContext= context;
mlist= list;
for(inti =0;i
money+= Integer.parseInt(mlist.get(i).getPrice()) * Integer.parseInt(mlist.get(i).getNum());
}
}
@Override
public intgetCount() {
returnmlist!=null?mlist.size() :0;
}
@Override
publicObjectgetItem(inti) {
return null;
}
@Override
public longgetItemId(inti) {
return0;
}
ViewHolderholder=null;
@Override
publicViewgetView(final inti,View view,ViewGroup viewGroup) {
if(view ==null) {
holder=newViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.item_goods,viewGroup, false);
holder.tv_add= (TextView) view.findViewById(R.id.tv_add);
holder.tv_minus= (TextView) view.findViewById(R.id.tv_minus);
holder.tv_price= (TextView) view.findViewById(R.id.tv_price);
holder.tv_num= (TextView) view.findViewById(R.id.tv_num);
view.setTag(holder);
}else{
holder= (ViewHolder) view.getTag();
}
holder.tv_price.setText(mlist.get(i).getPrice());
holder.tv_num.setText(mlist.get(i).getNum());
holder.tv_add.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
intnum = Integer.parseInt(mlist.get(i).getNum());
num++;
mlist.get(i).setNum(num +"");
holder.tv_num.setText(num +"");
money+= Integer.parseInt(mlist.get(i).getPrice());
notifyDataSetChanged();
if(listener!=null) {
listener.updatePrice(money);
}
}
});
holder.tv_minus.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
intnum = Integer.parseInt(mlist.get(i).getNum());
num--;
mlist.get(i).setNum(num +"");
holder.tv_num.setText(num +"");
notifyDataSetChanged();
money-= Integer.parseInt(mlist.get(i).getPrice());
if(listener!=null) {
listener.updatePrice(money);
}
}
});
returnview;
}
public classViewHolder {
publicTextViewtv_minus;
publicTextViewtv_add;
publicTextViewtv_price;
publicTextViewtv_num;
}