Android美食项目

项目简介

本项目是对本人Android学习的一个汇总,集合使用了大部分以前博客所写的技术,是一个完整的Android项目。
语言环境:Kotlin
框架:MVVM
使用的技术:
第三方库:Retrofit

JetPack:ROOM Database、Navigation Component、Data Binding、ViewModel、AndroidViewModel、LiveData、Recyclerview、Kotlin Coroutines

API接口
⽹址:https://spoonacular.com/food-api
API Key: bfc03d044f1e42f8ab2e4031dfebcdea
完整的api接口:
https://api.spoonacular.com/recipes/complexSearch?type=main course&addRecipeInformation=true&cuisines=Chinese&fillIngredients=true&apiKey=bfc03d044f1e42f8ab2e4031dfebcdea&number=1

项目展示:


主页


食谱详情页


收藏页面

1.准备工作,解析json数据,创建基本类

使用插件JsonToKotlinClass
fragment模板

class RecipeFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_recipe, container, false)
    }

}

2.第一步,搭建框架

使用Navigation,具体流程还可参考我的另一篇博客:https://www.jianshu.com/p/978951a2230f
基本流程:
1添加NavHost
2.添加⻝谱、喜欢和谚语的Fragment
3.添加NavHostFragment
4.添加BottomNavigationView和menu
5.关联BottomNavigationView和NavController
6.关联ActionBar和NavController
7.使⽤视图绑定访问xml中的控件

3.第二步,对Fragment进行布局,并用RecyclerView实现条目

RecyclerView 用法及缓存原理及性能优化可参考我的另一篇博客:https://www.jianshu.com/p/648e5ce98dfa
1.ShimmerRecyclerView的使⽤
2.ConstraintLayout约束布局使⽤

4.第三步,使用Okhttp和Retrofit进行数据请求

OkHttp、Gson、Retrofit的简单使用可参考我的另一篇博客:https://www.jianshu.com/p/b86bed8651d1
聚合数据API使⽤
OKHttp3请求数据
Gson解析Json数据
Json To Kotlin插件使⽤
Retrofit2请求数据的步骤

Service接口

interface FoodApi {
    //服务器地址api.spoonacular.com/recipes/complexSearch
    @GET("/recipes/complexSearch?fillIngredients=true&number=10&apiKey=bfc03d044f1e42f8ab2e4031dfebcdea&number=1")
    suspend fun fetchFoodRecipe(@Query("type")type: String): Response

}

RemoteRepository

class RemoteRepository {

        private val retrofit = Retrofit.Builder()
            .baseUrl("https://api.spoonacular.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        private val foodApi = retrofit.create(FoodApi::class.java)


    suspend fun fetchFoodRecipe(type: String): Response{
        return foodApi.fetchFoodRecipe(type)
    }
}

5.第四步,使用DataBinding进行数据和视图绑定显示美食条目并且封装网络类(sealed class)

声明data类变量名

绑定数据

绑定数据

通过url绑定图片数据,因为需要对url进行处理,所有使用@BindingAdapter注解
1.导入kotlin-kapt来使用@BindingAdapter


object FoodBindingAdapter {
    @JvmStatic
    @BindingAdapter("loadImageWithUrl")
    fun loadImageWithUrl(imageView: ImageView,url: String){
        Glide.with(imageView.context)
            .load(url)
            .into(imageView)
    }
}

总结:数据刷新流程

1.接受到下载数据

2.adapter进行刷新

3.执行createViewHolder和bindViewHolder

封装网络状态

sealed class NetworkResult(
        val data: T? = null,
        val message: String? = null){

    class Success(data: T): NetworkResult(data)
    class Error(errMsg: String):NetworkResult(message = errMsg)
    class Loading: NetworkResult()

}

6.第五步,使用room达到数据持久化

//数据仓库:实现数据的存取等
class LocalRepository(context: Context) {
    private val recipeDao = RecipeDatabase.getDatabase(context).getRecipeDao()

    //插入数据,重复则替换
    suspend fun insertRecipe(recipeEntity: RecipeEntity){
        recipeDao.insertRecipe(recipeEntity)
    }

    //查询数据
    fun getRecipes(type: String): Flow>{
        return recipeDao.getRecipes(type)
    }

    //更新数据
    suspend fun updateRecipe(recipeEntity: RecipeEntity){
        recipeDao.updateRecipe(recipeEntity)
    }
}
@Dao
interface RecipeDao {
    //插入数据,重复则替换
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertRecipe(recipeEntity: RecipeEntity)

    //查询数据
    @Query("select * from foodRecipeTable where type = :type")
    fun getRecipes(type: String): Flow>

    //更新数据
    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun updateRecipe(recipeEntity: RecipeEntity)
}
@TypeConverters(RecipeTypeConverter::class)
@Database(entities = [RecipeEntity::class],version = 1)
abstract class RecipeDatabase: RoomDatabase() {
    abstract fun getRecipeDao(): RecipeDao

    companion object{
        private var instance: RecipeDatabase? = null
        @Synchronized
        fun getDatabase(context: Context): RecipeDatabase{
            instance?.let {
                return it
            }
            return Room.databaseBuilder(context.applicationContext,
            RecipeDatabase::class.java,"foodRecipe_database")
                .build().apply {
                    instance = this
                }
        }
    }
}
@Entity(tableName = "foodRecipeTable")
class RecipeEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val type: String,
    val recipe: FoodRecipe
)
class RecipeTypeConverter {
    //foodRecipe -> String
    @TypeConverter
    fun foodRecipeToString(recipe: FoodRecipe): String{
        return Gson().toJson(recipe)
    }

    @TypeConverter
    fun stringToFoodRecipe(string: String): FoodRecipe{
        return Gson().fromJson(string,FoodRecipe::class.java)
    }
}

7.第六步,对Result类实现序列化来进行主页到详情页的信息传递

plugins {
    id 'kotlin-parcelize'
}
@Parcelize
data class Result(
    @SerializedName("aggregateLikes")
    val aggregateLikes: Int,
    @SerializedName("cheap")
    val cheap: Boolean,
    @SerializedName("cuisines")
    val cuisines: List,
    @SerializedName("dairyFree")
    val dairyFree: Boolean,
    @SerializedName("extendedIngredients")
    val extendedIngredients: List,
    @SerializedName("gaps")
    val gaps: String
): Parcelable


nav_graph添加后在recyclerview的adapter中传递数据


class DetailFragment : Fragment() {
    private lateinit var binding:FragmentDetailBinding
    private val recipeArgs: DetailFragmentArgs by navArgs()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentDetailBinding.inflate(inflater)
        return binding.root
    }

详情页中ViewPager的使用

遇到的问题:

dataBinding传递函数
recyclerview回调实现点击效果
view动画不改变view的真实位置
LayoutInflater中的的inflate方法



第一种方式填充视图,item布局中的根视图的layout_XX属性会被忽略掉,然后设置成默认的包裹内容方式
第二种方式,才会使用在xml中parent对viewHolder的约束对进行布局

项目地址:https://gitee.com/koocuu/MyFoodRecipe

你可能感兴趣的:(Android美食项目)