[Android Studio|Kotlin] RecyclerView, setOnClickListener
Published: 2022-02-18 18:57:34

Youtube: {% youtube 4o6QwVe_2Yg %} 

[app>values>themes>themes.xml]

```
        <!-- Customize your theme here. -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
``` 
[Gradle Scripts>build.gradle(Module:recyclerview.app)]

``` 
    // retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
```

[app>manifests>AndroidManifest.xml]

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.recyclerview">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Recyclerview">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application> 
</manifest>
```
[app>java>com.example...>ApiService]

```
package com.example.recyclerview

import retrofit2.Call
import retrofit2.http.GET

interface ApiService {
    @GET("/apptech")
    fun getPosts(): Call<MutableList<PostModel>>
}
```

[app>java>com.example...>MainActivity]

```
package com.example.recyclerview

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.recyclerview.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val recyclerView = findViewById<RecyclerView>(R.id.myRecyclerView)
        val serviceGenerator = ServiceGenerator.buildService(ApiService::class.java)
        val call = serviceGenerator.getPosts()
        call.enqueue(object : Callback<MutableList<PostModel>>{
                override fun onResponse(call: Call<MutableList<PostModel>>, response: Response<MutableList<PostModel>>) {
                    if (response.isSuccessful) {
                        recyclerView.apply {
                            layoutManager = LinearLayoutManager(this@MainActivity)
                            adapter = PostAdapter(response.body()!!)
                        }
                    }
                }

                override fun onFailure(call: Call<MutableList<PostModel>>, t: Throwable) {
                    t.printStackTrace()
                    Log.e("error", t.message.toString())
                }
            })
    }
}
```

[app>java>com.example...>PostAdapter]

```
package com.example.recyclerview

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView 
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView

class PostAdapter(val postModel: MutableList<PostModel>):RecyclerView.Adapter<PostAdapter.PostViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.card_post,parent,false)
        return PostViewHolder(view )
    }

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



    override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
        return holder.bindView(postModel[position])
    }

    inner class PostViewHolder(itemView: View ) : RecyclerView.ViewHolder(itemView) {
        private val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
        private val tvBody: TextView = itemView.findViewById(R.id.tvBody)
        private val tvTime: TextView = itemView.findViewById(R.id.tvTime)

        fun bindView(postModel: PostModel){
            tvTitle.text = postModel.apptech_brand
            tvBody.text = postModel.apptech_title
            tvTime.text = postModel.apptech_time
            // for setOnClickListener
            itemView.setOnClickListener {
                var url = "${postModel.apptech_url}"
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                ContextCompat.startActivity(itemView.context, intent, null)
            }
        }

    } 
}
```

[app>java>com.example...>PostModel]

```
package com.example.recyclerview

data class PostModel(
    val apptech_brand: String? = null,
    val apptech_title: String? = null,
    val apptech_period: String? = null,
    val apptech_point: Int? = null,
    val apptech_time: String? = null,
    val apptech_url: String? = null
)
```

[app>java>com.example...>ServiceGenerator]

```
package com.example.recyclerview

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ServiceGenerator {
    private val client = OkHttpClient.Builder().build()
    private val retrofit = Retrofit.Builder()
        .baseUrl("https://********.herokuapp.com")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    fun <T> buildService(service: Class<T>): T {
        return retrofit.create(service)
    }
}
```

[app>res>drawable>border_a.xml]
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFD0D0"></solid>
    <stroke android:width="3dp" android:color="#FF8484"/>
    <corners android:radius="15dp"/>
</shape>
```

[app>res>layout>activity_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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/myRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</FrameLayout>
```

[app>res>layout>card_post.xml]

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:paddingLeft="15dp"
    android:layout_marginTop="4dp"
    android:layout_marginBottom="4dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:orientation="horizontal"
    android:background="@drawable/border_a">

    <TextView
        android:id="@+id/tvTitle"
        tools:text="Hello Title"
        android:layout_width="80dp"
        android:layout_height="match_parent"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp" >

        <TextView
            android:id="@+id/tvBody"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            tools:text="Hello Body"
            android:textAlignment="center"/>

        <TextView
            android:id="@+id/tvTime"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textSize="14sp"
            tools:text="Hello Time"
            android:textAlignment="center"/> 
    </LinearLayout> 
</LinearLayout>
```