BusinessActivity.kt对底部布局点击的监听,弹出dialog并用RecycleView填充布局
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.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)
//微调底部的导航栏适配
if (checkDeviceHasNavigationBar(this)) {
fl_Container.setPadding(0, 0, 0, 48.dp2px())
}
vp.adapter = BusinessFragmentPagerAdapter()
tabs.setupWithViewPager(vp)
bottom.setOnClickListener(this)
}
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)
}
}
GoodsFragmentPresenter.kt清空购物车处理的逻辑
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.fragment.GoodsFragment
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")
//商品类型的集合
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
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)
}
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
}
}
}
Constants.kt常量的处理
package com.example.takeout.utils
class Constants {
companion object {
val ADD = 1
val MINUS = -1
}
}
CartRvAdapter.kt底部布局listview的布局,RecycleView的处理,有点击事件的处理和小红点的处理逻辑
package com.example.takeout.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.takeout.R
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.PriceFormater
class CartRvAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val goodsFragment: GoodsFragment
init {
goodsFragment = (context as BusinessActivity).fragments.get(0) as GoodsFragment
}
var cartList: ArrayList<GoodsInfo> = arrayListOf()
fun setCart(cartList: ArrayList<GoodsInfo>) {
this.cartList = cartList
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val itemView = LayoutInflater.from(context).inflate(R.layout.item_cart, parent, false)
return CartItemHolder(itemView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as CartItemHolder).bindData(cartList.get(position))
}
override fun getItemCount(): Int {
return cartList.size
}
inner class CartItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
override fun onClick(v: View?) {
var isAdd = false
when (v?.id) {
R.id.ib_add -> {
isAdd = true
doAddOperation()
}
R.id.ib_minus -> doMinusOperation()
}
processRedDotCount(isAdd) //红点处理
(context 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) {
//数量为1再减需要移除此条目
cartList.remove(goodsInfo)
if (cartList.size == 0) {
//最后一个类别移除后,关闭购物车
(context as BusinessActivity).showOrHideCart()
}
//删除缓存
// TakeoutApp.sInstance.deleteCacheSelectedInfo(goodsInfo.id)
} else {
//更新缓存
// TakeoutApp.sInstance.updateCacheSelectedInfo(goodsInfo.id, Constants.MINUS)
}
count--
goodsInfo.count = count
//购物车内部数量与价格
notifyDataSetChanged()
//右侧列表
goodsFragment.goodsAdapter.notifyDataSetChanged()
}
private fun doAddOperation() {
//数据层count
var count = goodsInfo.count
//更新缓存
// TakeoutApp.sInstance.updateCacheSelectedInfo(goodsInfo.id, Constants.ADD)
count++
goodsInfo.count = count
//购物车内部数量与价格
notifyDataSetChanged()
//右侧列表
goodsFragment.goodsAdapter.notifyDataSetChanged()
}
val tvName: TextView
val tvAllPrice: TextView
val tvCount: TextView
val ibAdd: ImageButton
val ibMinus: ImageButton
lateinit var goodsInfo: GoodsInfo
init {
tvName = itemView.findViewById(R.id.tv_name) as TextView
tvAllPrice = itemView.findViewById(R.id.tv_type_all_price) as TextView
tvCount = itemView.findViewById(R.id.tv_count) as TextView
ibAdd = itemView.findViewById(R.id.ib_add) as ImageButton
ibMinus = itemView.findViewById(R.id.ib_minus) as ImageButton
ibAdd.setOnClickListener(this)
ibMinus.setOnClickListener(this)
}
fun bindData(goodsInfo: GoodsInfo) {
this.goodsInfo = goodsInfo
tvName.text = goodsInfo.name
tvAllPrice.text = PriceFormater.format(goodsInfo.newPrice.toFloat() * goodsInfo.count)
tvCount.text = goodsInfo.count.toString()
}
}
}
cart_list.xml购物车模块的弹出的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#d7d4d4">
<ImageView
android:id="@+id/iv"
android:layout_width="5dp"
android:layout_height="20dp"
android:background="#227be1"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@+id/iv"
android:text="购物车"/>
<TextView
android:id="@+id/tvClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:drawableLeft="@mipmap/icon_clean_up"
android:layout_alignParentRight="true"
android:drawablePadding="5dp"
android:layout_marginRight="20dp"
android:text="清空"/>
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvCart"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
item_cart.xml购物车弹出窗口的RecycleView的布局的条目布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="60dp"
android:background="#fff"
android:gravity="center_vertical"
>
<TextView
android:id="@+id/tv_name"
android:layout_width="0dp"
android:layout_weight="1"
android:singleLine="true"
android:layout_height="wrap_content"
android:text="外带全家桶"
android:textSize="20sp"
android:textColor="#000"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"/>
<TextView
android:id="@+id/tv_type_all_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="¥60"
android:textSize="20sp"
android:textColor="#cd5656"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"/>
<LinearLayout
android:id="@+id/ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:orientation="horizontal">
<ImageButton
android:id="@+id/ib_minus"
android:layout_width="20dp"
android:layout_height="20dp"
android:visibility="visible"
android:background="@mipmap/button_minus"/>
<TextView
android:id="@+id/tv_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="0"
android:textColor="#000"
android:layout_marginLeft="5dp"
android:visibility="visible"
android:layout_gravity="center_vertical"
android:layout_marginRight="5dp"/>
<ImageButton
android:id="@+id/ib_add"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="20dp"
android:background="@mipmap/button_add"/>
</LinearLayout>
</LinearLayout>
效果如下: