日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Android中RecyclerView實(shí)現(xiàn)簡單購物車功能_Android

作者:楚木Ya ? 更新時間: 2022-04-16 編程語言

Android中RecyclerView實(shí)現(xiàn)簡單的購物車,供大家參考,具體內(nèi)容如下

我們知道在ListView中用setTag來解決Item的復(fù)用問題,但是RecyclerView中已經(jīng)幫我們封裝好了復(fù)用,如果在項(xiàng)目中出現(xiàn)了RecyclerView的復(fù)用性問題時我們又該如何解決.
先來看看效果圖:

圖片可能比較大也沒有動態(tài)圖片但效果是這樣的!幾天后就該有的都會有好了廢話不說,進(jìn)入正題

復(fù)用錯誤分析:

RecyclerView設(shè)置數(shù)據(jù)源時加入了if判斷,導(dǎo)致item重用時沒有進(jìn)入if判斷.繼續(xù)復(fù)用原來設(shè)置的UI屬性.簡單是說就是當(dāng)你滑動是你的是用的上一頁的子條目容器,RecyclerView默認(rèn)沒有設(shè)置選中數(shù)據(jù)的話是用上一頁條目的數(shù)據(jù).OK既然知道了問題的原因,那我們來裸代碼?.

具體操作:

//? 定義一個全局變量
// public SparseBooleanArray booleanArray = new SparseBooleanArray();
? ? ? ? //設(shè)置CheckBox的選中監(jiān)聽并給集合設(shè)置數(shù)據(jù)
? ? ? ? holder1.mCbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
? ? ? ? ? ? ? ? booleanArray.put(i, isChecked);

? ? ? ? ? ? }
? ? ? ? });
//設(shè)置數(shù)據(jù)
holder1.mCbx.setChecked(booleanArray.get(i));

購物車算錢:

購物車算錢這個就很簡單了,你不會什么也得會算錢?
直接上代碼:

//給CheckBox設(shè)置一個點(diǎn)擊事件并回調(diào)給界面的Activity
holder1.mCbx.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? if (mOnCBXOnClickListener != null) {
? ? ? ? ? ? ? ? ? ? mOnCBXOnClickListener.onClick(v, i);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? });

然后我們要注意的是double類型的數(shù)據(jù)會出現(xiàn)精度的問題,就比如算的好好的出現(xiàn)12.0000000002,等一系列長數(shù),所以為了解決這個問題我們這邊引入了DecimalFormat類.

// private double ?aggregateAmount;
?// DecimalFormat 類主要靠 # 和 0 兩種占位符號來指定數(shù)字長度。0 表示如果位數(shù)不足則以 0 填充,# 會把最后面的零默認(rèn)省略。
? ? ? ? //DecimalFormat df = new DecimalFormat("0.000");
? ? ? ? final DecimalFormat decimalFormat = new DecimalFormat("#.##");
? ? ? ? mRlvAdapter.setCBXOnClickListener(new RlvAdapter.onCBXOnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v, int i) {
? ? ? ? ? ? ? ? CheckBox cbx = v.findViewById(R.id.cbx);
? ? ? ? ? ? ? ? if (cbx.isChecked()) {

? ? ? ? ? ? ? ? ? ? aggregateAmount+=mRlvAdapter.mlist.get(i).getBuySpeciTotalPrice();
? ? ? ? ? ? ? ? ? ? String str = decimalFormat.format(aggregateAmount);
? ? ? ? ? ? ? ? ? ? money.setText("合計(jì)金額: ?"+str);
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? aggregateAmount-=mRlvAdapter.mlist.get(i).getBuySpeciTotalPrice();

? ? ? ? ? ? ? ? ? ? String sss = decimalFormat.format(aggregateAmount);
? ? ? ? ? ? ? ? ? ? money.setText("合計(jì)金額: ?"+sss);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? });

代碼比較簡單但自我感覺這種解決方式特別優(yōu)雅,特別棒!!?有沒有小紅花吶?

原文鏈接:https://blog.csdn.net/qq_44729989/article/details/90214071

欄目分類
最近更新