RecyclerView || #26

MainActivity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.neco_desarrollo.plantshandbook.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val adapter = PlantAdapter()
private val imageIdList = listOf(
R.drawable.plant1,
R.drawable.plant2,
R.drawable.plant3,
R.drawable.plant4,
R.drawable.plant5,
)
private var index = 0

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
init()
}

private fun init() {
binding.apply {
rcView.layoutManager = GridLayoutManager(this@MainActivity, 3)
rcView.adapter = adapter
buttonAdd.setOnClickListener {
if(index > 4) index = 0
val plant = Plant(imageIdList[index], "Plant $index")
adapter.addPlant(plant)
index++
}
}
}
}

Plant

data class Plant(val imageId: Int, val title: String)

PlantAdapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.neco_desarrollo.plantshandbook.databinding.PlantItemBinding
import java.util.ArrayList

class PlantAdapter: RecyclerView.Adapter<PlantAdapter.PlantHolder>() {
val plantList = ArrayList<Plant>()
class PlantHolder(item: View): RecyclerView.ViewHolder(item) {
val binding = PlantItemBinding.bind(item)
fun bind(plant: Plant) = with(binding){
im.setImageResource(plant.imageId)
tvTitle.text = plant.title
}
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlantHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.plant_item, parent, false)
return PlantHolder(view)
}

override fun onBindViewHolder(holder: PlantHolder, position: Int) {
holder.bind(plantList[position])
}

override fun getItemCount(): Int {
return plantList.size
}

fun addPlant(plant: Plant){
plantList.add(plant)
notifyDataSetChanged()
}
}

themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.PlantsHandBook" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/grey</item>
<item name="colorPrimaryVariant">@color/grey</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

plant_item.xml

<?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="wrap_content">

<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:cardCornerRadius="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:orientation="vertical">

<ImageView
android:id="@+id/im"
android:layout_width="match_parent"
android:layout_height="100dp"
app:srcCompat="@drawable/plant1" />

<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="sans-serif-condensed"
android:gravity="center"
android:text="TextView"
android:textColor="@color/black"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="grey">#8E8E8E</color>
</resources>

build.gradle (Module)

ВНИМАНИЕ!! Заменить applicationId на название вашего пакета!

plugins {
id 'com.android.application'
id 'kotlin-android'
}

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"

defaultConfig {
applicationId "название вашего пакета"
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}

buildFeatures{
viewBinding true
}
}

dependencies {

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.5.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

1 комментарий для “RecyclerView || #26”

  1. У меня ошибка в этой строке rcView.layoutManager лаяут манеджер горит красным. В чём может быть проблема?

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *