Koltin44.Takeout首页详情界面缓存的保存和读取的实现(30)

TakeoutApp.kt缓存的增删改查的实现

package com.example.takeout.utils

import android.app.Application
import cn.jpush.android.api.JPushInterface
import com.example.takeout.beans.User
import com.example.takeout.model.beans.CacheSelectedInfo
import java.util.concurrent.CopyOnWriteArrayList

class TakeoutApp : Application() {
    //点餐缓存集合
    val infos: CopyOnWriteArrayList<CacheSelectedInfo> = CopyOnWriteArrayList()

    /**
     * 根据Id查找商品信息
     */
    fun queryCacheSelectedInfoByGoodsId(goodsId: Int): Int {
        var count = 0
        for (i in 0..infos.size - 1) {
            val (_, _, goodsId1, count1) = infos[i]
            if (goodsId1 == goodsId) {
                count = count1
                break
            }
        }
        return count
    }

    /**
     * 根据类别查找
     */
    fun queryCacheSelectedInfoByTypeId(typeId: Int): Int {
        var count = 0
        for (i in 0..infos.size - 1) {
            val (_, typeId1, _, count1) = infos[i]
            if (typeId1 == typeId) {
                count = count + count1
            }
        }
        return count
    }

    /**
     * 根据店名查找点餐的数量
     */
    fun queryCacheSelectedInfoBySellerId(sellerId: Int): Int {
        var count = 0
        for (i in 0..infos.size - 1) {
            val (sellerId1, _, _, count1) = infos[i]
            if (sellerId1 == sellerId) {
                count = count + count1
            }
        }
        return count
    }

    /**
     * 购物车中继续添加商品
     */
    fun addCacheSelectedInfo(info: CacheSelectedInfo) {
        infos.add(info)
    }

    /**
     * 清空购物车
     */
    fun clearCacheSelectedInfo(sellerId: Int) {
        val temp = ArrayList<CacheSelectedInfo>()
        for (i in 0..infos.size - 1) {
            val info = infos[i]
            if (info.sellerId == sellerId) {
//                infos.remove(info)
                temp.add(info)
            }
        }
        infos.removeAll(temp)
    }

    /**
     * 删除条目
     */
    fun deleteCacheSelectedInfo(goodsId: Int) {
        for (i in 0..infos.size - 1) {
            val info = infos[i]
            if (info.goodsId == goodsId) {
                infos.remove(info)
                break
            }
        }
    }

    /**
     * 更新
     */
    fun updateCacheSelectedInfo(goodsId: Int, operation: Int) {
        for (i in 0..infos.size - 1) {
            var info = infos[i]
            if (info.goodsId == goodsId) {
                when (operation) {
                    Constants.ADD -> info.count = info.count + 1
                    Constants.MINUS -> info.count = info.count - 1
                }

            }
        }
    }

    companion object {
        var sUser: User = User()
        lateinit var sInstance: TakeoutApp
    }

    //应用程序的入口
    override fun onCreate() {
        super.onCreate()
        sInstance = this //设置成单例
        sUser.id = -1 //未登录用户id=-1
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

}

GoodsAdapter.kt缓存保存的实现

package com.example.takeout.ui.adapter

import android.graphics.Color
import android.graphics.Paint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.*
import android.widget.BaseAdapter
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.example.takeout.R
import com.example.takeout.model.beans.CacheSelectedInfo
import com.example.takeout.model.beans.GoodsInfo
import com.example.takeout.ui.activity.BusinessActivity
import com.example.takeout.ui.fragment.GoodsFragment
import com.example.takeout.utils.Constants
import com.example.takeout.utils.PriceFormater
import com.example.takeout.utils.TakeoutApp
import com.squareup.picasso.Picasso
import org.jetbrains.anko.find
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter

class GoodsAdapter(val context: FragmentActivity?, val goodsFragment: GoodsFragment) : BaseAdapter(), StickyListHeadersAdapter {

    val host = "http://127.0.0.1:8090/image?name="
    val DURATION: Long = 1000 //持续时间


    var goodsList: List<GoodsInfo> = ArrayList()

    fun setDatas(goodsInfoList: List<GoodsInfo>) {
        this.goodsList = goodsInfoList
        notifyDataSetChanged()
    }

    inner class GoodsItemHolder(itemView: View) : View.OnClickListener {

        override fun onClick(v: View?) {
            var isAdd: Boolean = false
            when (v?.id) {
                R.id.ib_add -> {
                    isAdd = true
                    doAddOperation()
                }
                R.id.ib_minus -> doMinusOperation()
            }
            processRedDotCount(isAdd)
            (goodsFragment.activity as BusinessActivity).updateCartUi();
        }

        private fun processRedDotCount(isAdd: Boolean) {
            //找到此商品属于的类别
            val typeId = goodsInfo.typeId
            //找到此类别在左侧列表中的位置(遍历)
            val typePosition = goodsFragment.goodsFragmentPresenter.getTypePositionByTypeId(typeId)
            //最后找出tvRedDotCount
            val goodsTypeInfo = goodsFragment.goodsFragmentPresenter.goodstypeList.get(typePosition)
            var redDotCount = goodsTypeInfo.redDotCount
            if (isAdd) {
                redDotCount++
            } else {
                redDotCount--
            }
            goodsTypeInfo.redDotCount = redDotCount
            //刷新左侧列表
            goodsFragment.goodsTypeAdapter.notifyDataSetChanged()
        }

        private fun doMinusOperation() {
            //改变count值
            var count = goodsInfo.count
            if (count == 1) {
                //最后一次点击减号执行动画集
                val hideAnimationSet: AnimationSet = getHideAnimation()
                tvCount.startAnimation(hideAnimationSet)
                btnMinus.startAnimation(hideAnimationSet)
                //删除缓存
                TakeoutApp.sInstance.deleteCacheSelectedInfo(goodsInfo.id)
            }else{
                //更新缓存
                TakeoutApp.sInstance.updateCacheSelectedInfo(goodsInfo.id, Constants.MINUS)
            }
            count--
            //改变数据层
            goodsInfo.count = count
            notifyDataSetChanged()
        }

        private fun doAddOperation() {
            //改变count值
            var count = goodsInfo.count
            if (count == 0) {
                //第一次点击加号执行动画集
                val showAnimationSet: AnimationSet = getShowAnimation()
                tvCount.startAnimation(showAnimationSet)
                btnMinus.startAnimation(showAnimationSet)
                //添加缓存
                TakeoutApp.sInstance.addCacheSelectedInfo(CacheSelectedInfo(goodsInfo.sellerId,goodsInfo.typeId,goodsInfo.id,1))
            }else{
                //更新缓存
                TakeoutApp.sInstance.updateCacheSelectedInfo(goodsInfo.id, Constants.ADD)
            }
            count++
            //改变数据层
            goodsInfo.count = count
            notifyDataSetChanged()

            //抛物线

            //1.克隆+号,并且添加到acitivty上
            var ib = ImageButton(context)
            //大小,位置、背景全部相同
            ib.setBackgroundResource(R.mipmap.button_add)
//            btnAdd.width
            val srcLocation = IntArray(2)
            btnAdd.getLocationInWindow(srcLocation)
            Log.e("location", srcLocation[0].toString() + ":" + srcLocation[1])
            ib.x = srcLocation[0].toFloat()
            ib.y = srcLocation[1].toFloat()
            (goodsFragment.activity as BusinessActivity).addImageButton(ib, btnAdd.width, btnAdd.height)
            //2.执行抛物线动画(水平位移,垂直加速位移)
            val destLocation = (goodsFragment.activity as BusinessActivity).getCartLocation()
            val parabolaAnim: AnimationSet = getParabolaAnimation(ib, srcLocation, destLocation)
            ib.startAnimation(parabolaAnim)
            //3.动画完成后回收克隆的+号
        }

        /**
         * 抛物线动画
         */
        private fun getParabolaAnimation(ib: ImageButton, srcLocation: IntArray, destLocation: IntArray): AnimationSet {
            val parabolaAnim: AnimationSet = AnimationSet(false)
            parabolaAnim.duration = DURATION
            val translateX = TranslateAnimation(
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, destLocation[0].toFloat() - srcLocation[0].toFloat(),
                Animation.ABSOLUTE, 0.0f,
                Animation.ABSOLUTE, 0.0f)
            translateX.duration = DURATION
            parabolaAnim.addAnimation(translateX)
            val translateY = TranslateAnimation(
                Animation.ABSOLUTE, 0F,
                Animation.ABSOLUTE, 0F,
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, destLocation[1].toFloat() - srcLocation[1].toFloat())
            translateY.setInterpolator(AccelerateInterpolator())
            translateY.duration = DURATION
            parabolaAnim.addAnimation(translateY)
            parabolaAnim.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationEnd(animation: Animation?) {
                    val viewParent = ib.parent
                    if (viewParent != null) {
                        (viewParent as ViewGroup).removeView(ib)
                    }
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }

                override fun onAnimationStart(animation: Animation?) {

                }
            })
            return parabolaAnim
        }

        /**
         * 隐藏动画
         */
        private fun getHideAnimation(): AnimationSet {
            var animationSet: AnimationSet = AnimationSet(false)
            animationSet.duration = DURATION
            val alphaAnim: Animation = AlphaAnimation(1f, 0.0f)
            alphaAnim.duration = DURATION
            animationSet.addAnimation(alphaAnim)
            val rotateAnim: Animation = RotateAnimation(720.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
            rotateAnim.duration = DURATION
            animationSet.addAnimation(rotateAnim)
            val translateAnim: Animation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 2.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f)
            translateAnim.duration = DURATION
            animationSet.addAnimation(translateAnim)
            return animationSet
        }

        /**
         * 动画
         */
        private fun getShowAnimation(): AnimationSet {
            var animationSet: AnimationSet = AnimationSet(false)
            animationSet.duration = DURATION
            //透明度
            val alphaAnim: Animation = AlphaAnimation(0.0f, 1.0f)
            alphaAnim.duration = DURATION
            animationSet.addAnimation(alphaAnim)
            //旋转
            val rotateAnim: Animation = RotateAnimation(0.0f, 720.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
            rotateAnim.duration = DURATION
            animationSet.addAnimation(rotateAnim)
            val translateAnim: Animation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 2.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f)
            translateAnim.duration = DURATION
            animationSet.addAnimation(translateAnim)
            return animationSet
        }

        val ivIcon: ImageView
        val tvName: TextView
        val tvForm: TextView
        val tvMonthSale: TextView
        val tvNewPrice: TextView
        val tvOldPrice: TextView
        val btnAdd: ImageButton
        val btnMinus: ImageButton
        val tvCount: TextView
        lateinit var goodsInfo: GoodsInfo

        init {
            ivIcon = itemView.find(R.id.iv_icon)
            tvName = itemView.find(R.id.tv_name)
            tvForm = itemView.find(R.id.tv_form)
            tvMonthSale = itemView.find(R.id.tv_month_sale)
            tvNewPrice = itemView.find(R.id.tv_newprice)
            tvOldPrice = itemView.find(R.id.tv_oldprice)
            tvCount = itemView.find(R.id.tv_count)
            btnAdd = itemView.find(R.id.ib_add)
            btnMinus = itemView.find(R.id.ib_minus)
            btnAdd.setOnClickListener(this)
            btnMinus.setOnClickListener(this)
        }

        fun bindData(goodsInfo: GoodsInfo) {
            this.goodsInfo = goodsInfo
            //图片路径http://127.0.0.1:8090/image?name=takeout/businessimg/goods/0.jpg
            Picasso.with(context).load(host + goodsInfo.icon).into(ivIcon)
            tvName.text = goodsInfo.name
//            tvForm.text = goodsInfo.form
            tvMonthSale.text = "月售${goodsInfo.monthSaleNum}份"
            tvNewPrice.text = PriceFormater.format(goodsInfo.newPrice.toFloat())
//            tvNewPrice.text = "$${goodsInfo.newPrice}"
            tvOldPrice.text = "¥${goodsInfo.oldPrice}"
            tvOldPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            if (goodsInfo.oldPrice > 0) {
                tvOldPrice.visibility = View.VISIBLE
            } else {
                tvOldPrice.visibility = View.GONE
            }
            tvCount.text = goodsInfo.count.toString()
            if (goodsInfo.count > 0) {
                tvCount.visibility = View.VISIBLE
                btnMinus.visibility = View.VISIBLE
            } else {
                tvCount.visibility = View.INVISIBLE
                btnMinus.visibility = View.INVISIBLE
            }
        }
    }

    override fun getCount(): Int {
        return goodsList.size
    }

    override fun getItem(position: Int): Any {
        return goodsList.get(position)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var itemView: View
        val goodsItemHolder: GoodsItemHolder
        if (convertView == null) {
            itemView = LayoutInflater.from(context).inflate(R.layout.item_goods, parent, false)
            goodsItemHolder = GoodsItemHolder(itemView)
            itemView.tag = goodsItemHolder
        } else {
            itemView = convertView
            goodsItemHolder = convertView.tag as GoodsItemHolder
        }
        goodsItemHolder.bindData(goodsList.get(position))
        return itemView
    }

    override fun getHeaderView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val goodsInfo: GoodsInfo = goodsList.get(position)
        val typeName = goodsInfo.typeName
        val textView: TextView = LayoutInflater.from(context).inflate(R.layout.item_type_header, parent, false) as TextView
        textView.text = typeName
        textView.setTextColor(Color.BLACK)
        return textView
    }

    override fun getHeaderId(position: Int): Long {
        val goodsInfo: GoodsInfo = goodsList.get(position)
        return goodsInfo.typeId.toLong()
    }
}

HomeRvAdapter.kt点击跳转到activity以前会先获取缓存的数据

package com.example.takeout.ui.adapter

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.daimajia.slider.library.SliderLayout
import com.daimajia.slider.library.SliderTypes.TextSliderView
import com.example.takeout.R
import com.example.takeout.model.beans.Seller
import com.example.takeout.ui.activity.BusinessActivity
import com.example.takeout.utils.TakeoutApp
import com.squareup.picasso.Picasso
import org.jetbrains.anko.find

class HomeRvAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    //定义常量
    companion object {
        val TYPE_TITLE = 0
        val TYPE_SELLER = 1
    }

    val host = "http://127.0.0.1:8090/image?name="

    var mDatas: ArrayList<Seller> = ArrayList()

    fun setData(data: ArrayList<Seller>) {
        this.mDatas = data
        notifyDataSetChanged()
    }

    /**
     * 不同position对应不同类型
     */
    override fun getItemViewType(position: Int): Int {
        if (position == 0) {
            return TYPE_TITLE
        } else {
            return TYPE_SELLER
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val viewType = getItemViewType(position)
        when (viewType) {
            TYPE_TITLE -> (holder as TitleHolder).bindData("我是title----------------------------------------")
            TYPE_SELLER -> (holder as SellerHolder).bindData(mDatas[position - 1])
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            TYPE_TITLE -> return TitleHolder(View.inflate(context, R.layout.item_title, null))
            TYPE_SELLER -> return SellerHolder(View.inflate(context, R.layout.item_seller, null))
            else -> return TitleHolder(View.inflate(context, R.layout.item_home_common, null))
        }
    }

    override fun getItemCount(): Int {
        if (mDatas.size > 0) {
            return mDatas.size + 1
        } else {
            return 0
        }
    }

    //内部类,商家的holder
    inner class SellerHolder(item: View) : RecyclerView.ViewHolder(item) {
        val tvTitle: TextView
        val ivLogo: ImageView
        val rbScore: RatingBar
        val tvSale: TextView
        val tvSendPrice: TextView
        val tvDistance: TextView
        lateinit var mSeller: Seller

        init {
            tvTitle = item.find(R.id.tv_title)
            ivLogo = item.find(R.id.seller_logo)
            rbScore = item.find(R.id.ratingBar)
            tvSale = item.find(R.id.tv_home_sale)
            tvSendPrice = item.find(R.id.tv_home_send_price)
            tvDistance = item.find(R.id.tv_home_distance)
            item.setOnClickListener {
                val intent: Intent = Intent(context, BusinessActivity::class.java)//去取小明在田老师这家店是否有缓存信息
                //逐层读取,判断整个这家店是否有缓存
                var hasSelectInfo = false
                val count = TakeoutApp.sInstance.queryCacheSelectedInfoBySellerId(mSeller.id.toInt())
                if (count > 0) {
                    hasSelectInfo = true
                }
                intent.putExtra("seller", mSeller)
                intent.putExtra("hasSelectInfo", hasSelectInfo)

                context.startActivity(intent)
            }
        }

        fun bindData(seller: Seller) {
            this.mSeller = seller
            tvTitle.text = seller.name
            //图片路径http://127.0.0.1:8090/image?name=takeout/imgs/seller/3.jpg
            println("seller.ensure====" + seller.ensure)
            Picasso.with(context).load(host + seller.ensure).into(ivLogo)
            rbScore.rating = seller.score.toFloat()
            tvSale.text = "月售${seller.sale}单"
            tvSendPrice.text = "¥${seller.sendPrice}起送/配送费¥${seller.deliveryFee}"
        }
    }

    //存放图片的url和名称
    var url_maps: HashMap<String, Int> = HashMap()

    //内部类,title的holder
    inner class TitleHolder(item: View) : RecyclerView.ViewHolder(item) {

        val sliderLayout: SliderLayout

        init {
            sliderLayout = item.findViewById(R.id.slider)
        }

        fun bindData(data: String) {
            if (url_maps.size == 0) {
                url_maps.put("Hannibal", R.mipmap.pic1);
                url_maps.put("Big Bang Theory", R.mipmap.pic2);
                url_maps.put("House of Cards", R.mipmap.pic3);
                url_maps.put("Game of Thrones", R.mipmap.pic4);
                for ((key, value) in url_maps) {
                    val textSlideView: TextSliderView = TextSliderView(context)
                    textSlideView.description(key).image(value)
                    sliderLayout.addSlider(textSlideView)
                }

            }
        }
    }
}

BusinessActivity.kt会读取adapter item点击跳转过来的数据

package com.example.takeout.ui.activity

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.takeout.R
import com.example.takeout.model.beans.Seller
import com.example.takeout.ui.adapter.CartRvAdapter
import com.example.takeout.ui.fragment.CommentsFragment
import com.example.takeout.ui.fragment.GoodsFragment
import com.example.takeout.ui.fragment.SellerFragment
import com.example.takeout.utils.PriceFormater
import kotlinx.android.synthetic.main.activity_business.*

class BusinessActivity : AppCompatActivity() , View.OnClickListener{
    var bottomSheetView: View? = null
    lateinit var rvCart: RecyclerView
    lateinit var cartAdapter: CartRvAdapter
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.bottom -> showOrHideCart()
            R.id.tvSubmit -> {
//                val intent : Intent = Intent(this, ConfirmOrderActivity::class.java)
//                startActivity(intent)
            }
        }
    }

    /***
     * 显示底部购物车的dialog
     */
    fun showOrHideCart() {
        if (bottomSheetView == null) {
            //加载要显示的布局
            bottomSheetView = LayoutInflater.from(this).inflate(R.layout.cart_list, window.decorView as ViewGroup, false)
            rvCart = bottomSheetView!!.findViewById(R.id.rvCart) as RecyclerView
            rvCart.layoutManager = LinearLayoutManager(this)
            cartAdapter = CartRvAdapter(this)
            rvCart.adapter = cartAdapter
            val tvClear: TextView = bottomSheetView!!.findViewById(R.id.tvClear) as TextView
            tvClear.setOnClickListener {
                var builder = AlertDialog.Builder(this)
                builder.setTitle("确认都不吃了么?")
                builder.setPositiveButton("是,我要减肥", object : DialogInterface.OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        //开始清空购物车,把购物车中商品的数量重置为0
                        val goodsFragment: GoodsFragment = fragments.get(0) as GoodsFragment
                        goodsFragment.goodsFragmentPresenter.clearCart()
                        cartAdapter.notifyDataSetChanged()
                        //关闭购物车
                        showOrHideCart()
                        //刷新右侧
                        goodsFragment.goodsAdapter.notifyDataSetChanged()
                        //清空所有红点
                        clearRedDot()
                        goodsFragment.goodsTypeAdapter.notifyDataSetChanged()
                        //更新下方购物篮
                        updateCartUi()
                    }


                })
                builder.setNegativeButton("不,我还要吃", object : DialogInterface.OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {

                    }
                })
                builder.show()
            }
        }
        //判断BottomSheetLayout内容是否显示
        if (bottomSheetLayout.isSheetShowing) {
            //关闭内容显示
            bottomSheetLayout.dismissSheet()
        } else {
            //显示BottomSheetLayout里面的内容
            val goodsFragment: GoodsFragment = fragments.get(0) as GoodsFragment
            val cartList = goodsFragment.goodsFragmentPresenter.getCartList()
            cartAdapter.setCart(cartList)
            if (cartList.size > 0) {
                bottomSheetLayout.showWithSheetView(bottomSheetView)
            }
        }
    }

    private fun clearRedDot() {
        val goodsFragment: GoodsFragment = fragments.get(0) as GoodsFragment
        val goodstypeList = goodsFragment.goodsFragmentPresenter.goodstypeList
        for (i in 0 until goodstypeList.size) {
            val goodsTypeInfo = goodstypeList.get(i)
            goodsTypeInfo.redDotCount = 0
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_business)
        processIntent()
        //微调底部的导航栏适配
        if (checkDeviceHasNavigationBar(this)) {
            fl_Container.setPadding(0, 0, 0, 48.dp2px())
        }

        vp.adapter = BusinessFragmentPagerAdapter()
        tabs.setupWithViewPager(vp)
        bottom.setOnClickListener(this)
    }

    var hasSelectInfo = false
    lateinit var seller: Seller
    private fun processIntent() {
        if (intent.hasExtra("hasSelectInfo")) {
            hasSelectInfo = intent.getBooleanExtra("hasSelectInfo", false)
            seller = intent.getSerializableExtra("seller") as Seller
            tvDeliveryFee.text = "另需配送费" + PriceFormater.format(seller.deliveryFee.toFloat())
            tvSendPrice.text = PriceFormater.format(seller.sendPrice.toFloat()) + "起送"
        }
    }

    val fragments = listOf<Fragment>(GoodsFragment(), SellerFragment(), CommentsFragment())
    val titles = listOf<String>("商品", "商家", "评论")

    /**
     * 把转化功能添加到Int类中作为扩展函数
     */
    fun Int.dp2px(): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            toFloat(), resources.displayMetrics
        ).toInt()

    }

    //获取是否存在NavigationBar
    fun checkDeviceHasNavigationBar(context: Context): Boolean {
        var hasNavigationBar = false
        val rs = context.getResources()
        val id = rs.getIdentifier("config_showNavigationBar", "bool", "android")
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id)
        }
        try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val m = systemPropertiesClass.getMethod("get", String::class.java)
            val navBarOverride = m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String
            if ("1" == navBarOverride) {
                hasNavigationBar = false
            } else if ("0" == navBarOverride) {
                hasNavigationBar = true
            }
        } catch (e: Exception) {

        }

        return hasNavigationBar
    }

    inner class BusinessFragmentPagerAdapter : FragmentPagerAdapter(supportFragmentManager) {

        override fun getPageTitle(position: Int): CharSequence {
            return titles.get(position)
        }

        override fun getItem(position: Int): Fragment {
            return fragments.get(position)
        }

        override fun getCount(): Int {
            return titles.size
        }

    }

    /**
     * 增加的按钮
     */
    fun addImageButton(ib: ImageButton, width: Int, height: Int) {
        fl_Container.addView(ib, width, height)
    }

    fun getCartLocation(): IntArray {
        val destLocation = IntArray(2)
        imgCart.getLocationInWindow(destLocation)
        return destLocation
    }

    /**
     * 更新购物车
     */
    fun updateCartUi() {
        //更新数量,更新总价
        var count = 0
        var countPrice = 0.0f
        //哪些商品属于购物车?
        val goodsFragment: GoodsFragment = fragments.get(0) as GoodsFragment
        val cartList = goodsFragment.goodsFragmentPresenter.getCartList()
        for (i in 0 until cartList.size) {
            val goodsInfo = cartList.get(i)
            count += goodsInfo.count
            countPrice += goodsInfo.count * goodsInfo.newPrice.toFloat()
        }
        tvSelectNum.text = count.toString()
        if (count > 0) {
            tvSelectNum.visibility = View.VISIBLE
        } else {
            tvSelectNum.visibility = View.GONE
        }
        tvCountPrice.text = PriceFormater.format(countPrice)
    }
}

CacheSelectedInfo.kt点餐缓存的bean文件

package com.example.takeout.model.beans

/*
    点餐缓存
 */
data class CacheSelectedInfo(var sellerId: Int, var typeId: Int, var goodsId: Int, var count: Int) {
//    val  sellerId = 0  //田老师店
//    val userId = 38   //小明
//    val typeId = 0   //粗粮主食
//    val goodsId = 0  //馒头
//    val count = 0     //馒头数量
}

GoodsFragmentPresenter.kt业务逻辑的操作,直接读取缓存的数据,并且更新购物车的UI

package com.example.takeout.presenter

import android.util.Log
import com.example.takeout.model.beans.GoodsInfo
import com.example.takeout.model.beans.GoodsTypeInfo
import com.example.takeout.ui.activity.BusinessActivity
import com.example.takeout.ui.fragment.GoodsFragment
import com.example.takeout.utils.TakeoutApp
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONObject

class GoodsFragmentPresenter(val goodsFragment: GoodsFragment) : NetPresenter() {

    var goodstypeList: List<GoodsTypeInfo> = arrayListOf()
    val allTypeGoodsList: ArrayList<GoodsInfo> = arrayListOf()

    //连接服务器拿到此商家所有商品
    fun getBusinessInfo() {
        val businessCall = takeoutService.getBusinessInfo()
        businessCall.enqueue(callback)
    }


    override fun parserJson(json: String) {
        val gson = Gson()
        val jsoObj = JSONObject(json)
        val allStr = jsoObj.getString("list")
        val hasSelectInfo = (goodsFragment.activity as BusinessActivity).hasSelectInfo //是否有点餐记录
        //List<GoodsTypeInfo>
        //商品类型的集合
        goodstypeList = gson.fromJson(allStr, object : TypeToken<List<GoodsTypeInfo>>() {
        }.type)
        Log.e("business", "该商家一共有" + goodstypeList.size + "个类别商品")
        for (i in 0 until goodstypeList.size) {
            val goodsTypeInfo = goodstypeList.get(i)
            var aTypeCount = 0
            //如果缓存有数据就从缓存中读取数据
            if(hasSelectInfo){
                aTypeCount = TakeoutApp.sInstance.queryCacheSelectedInfoByTypeId(goodsTypeInfo.id)
                goodsTypeInfo.redDotCount = aTypeCount  //一个类别的记录,红点的个数
            }
            val aTypeList: List<GoodsInfo> = goodsTypeInfo.list
            for (j in 0 until aTypeList.size) {
                val goodsInfo = aTypeList.get(j)
                //建立双向绑定关系
                goodsInfo.typeName = goodsTypeInfo.name
                goodsInfo.typeId = goodsTypeInfo.id
            }
            allTypeGoodsList.addAll(goodsTypeInfo.list)
        }
        //更新购物车ui
        (goodsFragment.activity as BusinessActivity).updateCartUi()
        goodsFragment.onLoadBusinessSuccess(goodstypeList, allTypeGoodsList)
    }

    //根据商品类别id找到此类别第一个商品的位置
    fun getGoodsPositionByTypeId(typeId: Int): Int {
        var position = -1 //-1表示未找到
        for(j in 0 until  allTypeGoodsList.size){
            val goodsInfo = allTypeGoodsList.get(j)
            if(goodsInfo.typeId == typeId){
                position = j
                break;
            }
        }
        return position
    }

    //根据类别id找到其在左侧列表中的position,遍历左侧的列表
    fun getTypePositionByTypeId(newTypeId: Int):Int {
        var position = -1 //-1表示未找到
        for(i in 0 until  goodstypeList.size){
            val goodsTypeInfo = goodstypeList.get(i)
            if(goodsTypeInfo.id == newTypeId){
                position = i
                break;
            }
        }
        return position
    }

    fun getCartList() : ArrayList<GoodsInfo> {
        val cartList = arrayListOf<GoodsInfo>()
        //count >0的为购物车商品
        for(j in 0 until  allTypeGoodsList.size){
            val goodsInfo = allTypeGoodsList.get(j)
            if(goodsInfo.count>0){
                cartList.add(goodsInfo)
            }
        }
        return cartList
    }

    fun clearCart() {
        val cartList = getCartList()
        for(j in 0 until  cartList.size) {
            val goodsInfo = cartList.get(j)
            goodsInfo.count = 0
        }
    }
}

CartRvAdapter.购物车的数据,更新购物车的缓存

package com.example.takeout.ui.adapter

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.daimajia.slider.library.SliderLayout
import com.daimajia.slider.library.SliderTypes.TextSliderView
import com.example.takeout.R
import com.example.takeout.model.beans.Seller
import com.example.takeout.ui.activity.BusinessActivity
import com.example.takeout.utils.TakeoutApp
import com.squareup.picasso.Picasso
import org.jetbrains.anko.find

class HomeRvAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    //定义常量
    companion object {
        val TYPE_TITLE = 0
        val TYPE_SELLER = 1
    }

    val host = "http://127.0.0.1:8090/image?name="

    var mDatas: ArrayList<Seller> = ArrayList()

    fun setData(data: ArrayList<Seller>) {
        this.mDatas = data
        notifyDataSetChanged()
    }

    /**
     * 不同position对应不同类型
     */
    override fun getItemViewType(position: Int): Int {
        if (position == 0) {
            return TYPE_TITLE
        } else {
            return TYPE_SELLER
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val viewType = getItemViewType(position)
        when (viewType) {
            TYPE_TITLE -> (holder as TitleHolder).bindData("我是title----------------------------------------")
            TYPE_SELLER -> (holder as SellerHolder).bindData(mDatas[position - 1])
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            TYPE_TITLE -> return TitleHolder(View.inflate(context, R.layout.item_title, null))
            TYPE_SELLER -> return SellerHolder(View.inflate(context, R.layout.item_seller, null))
            else -> return TitleHolder(View.inflate(context, R.layout.item_home_common, null))
        }
    }

    override fun getItemCount(): Int {
        if (mDatas.size > 0) {
            return mDatas.size + 1
        } else {
            return 0
        }
    }

    //内部类,商家的holder
    inner class SellerHolder(item: View) : RecyclerView.ViewHolder(item) {
        val tvTitle: TextView
        val ivLogo: ImageView
        val rbScore: RatingBar
        val tvSale: TextView
        val tvSendPrice: TextView
        val tvDistance: TextView
        lateinit var mSeller: Seller

        init {
            tvTitle = item.find(R.id.tv_title)
            ivLogo = item.find(R.id.seller_logo)
            rbScore = item.find(R.id.ratingBar)
            tvSale = item.find(R.id.tv_home_sale)
            tvSendPrice = item.find(R.id.tv_home_send_price)
            tvDistance = item.find(R.id.tv_home_distance)
            item.setOnClickListener {
                val intent: Intent = Intent(context, BusinessActivity::class.java)//去取小明在田老师这家店是否有缓存信息
                //逐层读取,判断整个这家店是否有缓存
                var hasSelectInfo = false
                val count = TakeoutApp.sInstance.queryCacheSelectedInfoBySellerId(mSeller.id.toInt())
                if (count > 0) {
                    hasSelectInfo = true
                }
                intent.putExtra("seller", mSeller)
                intent.putExtra("hasSelectInfo", hasSelectInfo)

                context.startActivity(intent)
            }
        }

        fun bindData(seller: Seller) {
            this.mSeller = seller
            tvTitle.text = seller.name
            //图片路径http://127.0.0.1:8090/image?name=takeout/imgs/seller/3.jpg
            println("seller.ensure====" + seller.ensure)
            Picasso.with(context).load(host + seller.ensure).into(ivLogo)
            rbScore.rating = seller.score.toFloat()
            tvSale.text = "月售${seller.sale}单"
            tvSendPrice.text = "¥${seller.sendPrice}起送/配送费¥${seller.deliveryFee}"
        }
    }

    //存放图片的url和名称
    var url_maps: HashMap<String, Int> = HashMap()

    //内部类,title的holder
    inner class TitleHolder(item: View) : RecyclerView.ViewHolder(item) {

        val sliderLayout: SliderLayout

        init {
            sliderLayout = item.findViewById(R.id.slider)
        }

        fun bindData(data: String) {
            if (url_maps.size == 0) {
                url_maps.put("Hannibal", R.mipmap.pic1);
                url_maps.put("Big Bang Theory", R.mipmap.pic2);
                url_maps.put("House of Cards", R.mipmap.pic3);
                url_maps.put("Game of Thrones", R.mipmap.pic4);
                for ((key, value) in url_maps) {
                    val textSlideView: TextSliderView = TextSliderView(context)
                    textSlideView.description(key).image(value)
                    sliderLayout.addSlider(textSlideView)
                }

            }
        }
    }
}

效果如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值