无名之辈的Android之路

Android实战:美食项目(五)

2021-09-15  本文已影响0人  搬码人

Ingredient板块额搭建

拖入一个recyclerView并命名

ingredientRecyclerView

ingredient_item.xml的搭建

ingredient_item.xml

圆角边框的设计

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="22dp"/>
    <solid android:color="#29262E"/>

</shape>
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="ingredient"
            type="com.example.foodresp.data.model.ExtendedIngredient" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <View
            android:id="@+id/view10"
            android:layout_width="95dp"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginEnd="16dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/ingredient_round_shape"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/icon"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginTop="16dp"
            android:scaleType="centerCrop"
            app:layout_constraintEnd_toEndOf="@+id/view10"
            loadIngredientImageWithName="@{ingredient.image}"
            app:layout_constraintStart_toStartOf="@+id/view10"
            app:layout_constraintTop_toTopOf="@+id/view10"
            app:srcCompat="@drawable/ic_launcher_background" />

        <TextView
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:gravity="center"
            android:text="@{ingredient.name}"
            tools:text="TextView"
            android:textColor="#D8D8D8"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/unit"
            app:layout_constraintEnd_toEndOf="@+id/view10"
            app:layout_constraintStart_toStartOf="@+id/view10"
            app:layout_constraintTop_toBottomOf="@+id/icon" />

        <TextView
            android:id="@+id/amount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="16dp"
            tools:text="123"
            android:textColor="#DCD79E"
            android:text="@{String.valueOf(ingredient.amount)}"
            app:layout_constraintBottom_toBottomOf="@+id/view10"
            app:layout_constraintEnd_toStartOf="@+id/unit"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/view10" />

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="kg"
            android:text="@{ingredient.unit}"
            android:textColor="#DCD79E"
            app:layout_constraintEnd_toStartOf="@+id/view10"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/amount"
            app:layout_constraintTop_toTopOf="@+id/amount" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

用databinding的方式在ingredient_item.xml中绑定数据,因为前方
已经提及过所以这里不在详解,只做图片绑定的详解。
通过打印图片地址可知,图片地址是由一串固定地址和图片名.jpg构成,所以我们只需要在xml文件中调用BindingAdapter中的 loadIngredientImageWithName方法时传递image即可

ingredient_item.xml

BindingAdapter类中

 @JvmStatic
    @BindingAdapter("loadIngredientImageWithName")
    fun loadIngredientImageWithName(imageView: ImageView,name:String){
        //将url对应的图片下载下来 显示到imageView上
        //Glide
        val imageBaseUrl = "https://spoonacular.com/cdn/ingredients_250x250/"
        Glide.with(imageView.context)
                .load(imageBaseUrl+name)
                //设置默认图片 未加载完成时显示的图片
                .placeholder(R.drawable.ic_launcher_background)
                .into(imageView)
    }

收藏功能的完善

前面讲到了收藏数据库的搭建,这里对收藏功能的进一步完善。
创建FavoriteViewModel

/**
 *@Description
 *@Author PC
 *@QQ 1578684787
 */
class FavoriteViewModel(application: Application):AndroidViewModel(application) {
    private val localRepository = LocalRepository(application)
    val favoriteRecipes:MutableLiveData<List<FavoriteEntity>> = MutableLiveData()

    //查询所有收藏的食谱
    fun readFavorites(){
        viewModelScope.launch {
            localRepository.getAllFavorites().collect {
//                val resultList = mutableListOf<Result>()
//                it.forEach{entity ->
//                    resultList.add(entity.result)
//                }
                favoriteRecipes.value = it
            }
        }
    }
    //插入收藏的食谱
    fun insertFavorite(result:Result){
        viewModelScope.launch {
            val favoriteEntity = FavoriteEntity(0,result)
            localRepository.insertFavorite(favoriteEntity)
        }
    }
    //删除收藏的食谱
    fun deleteFavorite(favoriteEntity: FavoriteEntity){
        viewModelScope.launch {
            localRepository.deleteFavorite(favoriteEntity)
        }
    }

}

添加资源文件favorite_like_selector.xml ->当点击收藏按钮的时候按钮图片颜色更改为黄色,取消收藏后按钮颜色恢复(其实这里就是根据点击状态设置两种不同的图片)。


favorite_like_selector.xml
fragment_detail.xml

收藏页面额每个Item的搭建


image.png

向左滑动删除功能的实现

 /**
     * 滑动删除
     */
    private fun swipeToDelete(){
        val itemTouchHelper = ItemTouchHelper(object :ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT){
            override fun onMove(
                    recyclerView: RecyclerView,
                    viewHolder: RecyclerView.ViewHolder,
                    target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //获取滑动的位置
                val index = viewHolder.adapterPosition
                //将数据从数据源中删除
                val data = favoriteViewModel.favoriteRecipes.value!![index]
                favoriteViewModel.deleteFavorite(data)
                //弹出提示信息
               Toast.makeText(requireContext(),"Delete Finished!",Toast.LENGTH_LONG).show()
            }

        })
        //将滑动事件绑定到recyclerView上
        itemTouchHelper.attachToRecyclerView(binding.recyclerView)
    }

收藏页面的优化

点击收藏页面的Item将进入详情页面,这一功能与前方点击食谱进入详情页面的实现一模一样,这里不在作详细介绍,简单的给出实现步骤。

1、在navigation中
在两个页面之间添加跳转事件

image.png
2、在FavoriteAdapter中
在绑定数据时添加点击事件实现跳转(注:这里的跳转是带有数据的跳转)
FavoriteAdapter
3、关于定义参数接受传递过来的值在之前的Recipes页面跳转到Detail页面中已经实现过了,这里可以复用(不需要再次设置参数接受值)。

favorite_item.xml在运行后出现布局混乱

解决方式:
1、使用常规的绑定方式,不使用viewbinding
2、

image.png

项目完整代码

上一篇下一篇

猜你喜欢

热点阅读