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<FoodRecipe>

}

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<FoodRecipe>{
        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<T>(
        val data: T? = null,
        val message: String? = null){

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

}

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<List<RecipeEntity>>{
        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<List<RecipeEntity>>

    //更新数据
    @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<String>,
    @SerializedName("dairyFree")
    val dairyFree: Boolean,
    @SerializedName("extendedIngredients")
    val extendedIngredients: List<ExtendedIngredient>,
    @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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容