Для создания программы "Книга рецептов" на языке Kotlin в Android Studio выполните следующие шаги:
-
Установите и настройте Android Studio: https://developer.android.com/studio
-
Создайте новый проект и установите язык программирования Kotlin, минимальную версию SDK и готовый шаблон для навигации.
-
Установите библиотеки для работы с API и изображениями. В файле build.gradle (Module) добавьте следующие зависимости:
dependencies {
...
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2"
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
}
- Разработайте третий экран с изображением блюда и текстовым описанием рецепта. Создайте новый
Fragment и добавьте связанный файл макета.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.recipe.RecipeFragment">
<ImageView
android:id="@+id/imageView_recipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="@+id/textView_recipe_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
app:layout_constraintTop_toBottomOf="@id/imageView_recipe"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
- Разработайте второй экран со списком рецептов. Создайте адаптер и ViewHolder для отображения рецептов в RecyclerView и добавьте ViewModel для работы с тем же макетом файла.
class RecipeAdapter(private var recipeList: List<Recipe>) : RecyclerView.Adapter<RecipeAdapter.RecipeViewHolder>() {
inner class RecipeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textViewName: TextView = itemView.findViewById(R.id.recipe_name)
val imageView: ImageView = itemView.findViewById(R.id.recipe_image)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.recipe_item, parent, false)
return RecipeViewHolder(itemView)
}
override fun onBindViewHolder(holder: RecipeViewHolder, position: Int) {
val currentItem = recipeList[position]
holder.textViewName.text = currentItem.name
Glide.with(holder.itemView)
.load(currentItem.imageUrl)
.into(holder.imageView)
}
}
-
Зарегистрируйтесь на сайте https://developer.edamam.com/edamam-docs-recipe-api, чтобы получить ключ API и идентификатор приложения.
-
Создайте интерфейс Retrofit для работы с API и сервис для выпуска запросов.
interface RecipeApi {
@GET("search/")
suspend fun getRecipes(
@Query("app_id") appId: String,
appQuery("app_key") appKey: String,
appQuery("q") query: String
): Response<RecipeResponse>
}
- В файле ViewModel вы полную И оценку рецепты API и передать его по типу рецептов.
class RecipeViewModel : ViewModel() {
private val _recipes = MutableLiveData<List<Recipe>>()
val recipes: LiveData<List<Recipe>> get() = _recipes
suspend fun getRecipes() {
val recipeResponse = RecipeApiService.instance.getRecipes(API_ID, API_KEY, "shrimp")
if (recipeResponse.isSuccessful && recipeResponse.body() != null) {
_recipes.value = recipeResponse.body()!!.hits.map { it.recipe }
}
}
}
- Разработайте основной фрагмент первого экрана с кнопкой добро_пожаловать:
<fragment_main.xml>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.MainFragment">
<Button
android:id="@+id/button_enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</FrameLayout>
- Добавьте обработчики нажатий кнопок для перехода между фрагментами и подгрузки рецептов:
button_enter.setOnClickListener {
findNavController().navigate(R.id.action_mainFragment_to_recipeListFragment)
}
Следуя указанным шагам и заполнив ключевые части кода, вы создадите функциональное мобильное приложение "Книга рецептов" на платформе Android в Android Studio, используя Kotlin. Приложение будет содержать приветственный экран с кнопкой перехода на второй экран, страницу с перечнем рецептов, взятую с сервера с помощью API, а также страницу с изображением и описанием рецепта с сервера.