RecyclerView:没有连接适配器;设置onClickListener

时间:2018-01-24 01:34:58

标签: java android android-recyclerview kotlin

当我尝试在ViewHolder中实现onClickListener时,RecyclerView似乎停止工作。我无法弄清楚原因。

我尝试使用runOnUiThread来设置适配器。我也尝试在onCreate中将适配器设置为null,但这些解决方案似乎都没有工作。

我已经查看了其他类似问题的堆栈溢出帖子,但找不到合适的解决方案来实现此功能。

MainActivity.kt

package com.example.eijaz.popularmovies

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.io.IOException
import android.support.v7.widget.LinearLayoutManager
import com.google.gson.GsonBuilder
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import java.util.logging.Logger.global


class MainActivity : AppCompatActivity() {

    val URL_MAIN = "http://api.themoviedb.org/3"
    val POPULAR_MOVIES = "/movie/popular"
    val TOP_RATED_MOVIES = "movie/top_rated"

    val URL_INDIVIDUAL_MOVIE = "http://image.tmdb.org/t/p/"
    val POSTER_SIZE = "w185"

    val ENTER_API_KEY = "?api_key="
    val API_KEY = "67bfdc871eabed5845200d39e64ed6e5"

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

        fetchJson()

        rv_poster_list.layoutManager = GridLayoutManager(this, 2)
    }

    fun fetchJson() {
        println("Attempting to Fetch JSON")

        val request = Request.Builder().url(URL_MAIN + POPULAR_MOVIES + ENTER_API_KEY + API_KEY).build()

        val client = OkHttpClient()
        client.newCall(request).enqueue(object: Callback {
            override fun onResponse(call: Call?, response: Response?) {
                val body = response?.body()?.string()
                println(body)

                val gson = GsonBuilder().create()

                val homeFeed = gson.fromJson(body, HomeFeed::class.java)

                runOnUiThread {
                    rv_poster_list.adapter = MovieAdapter(homeFeed)
                }
            }

            override fun onFailure(call: Call?, e: IOException?) {
                println("Failed to execute request")
            }
        })
    }
}


ackage com.example.eijaz.popularmovies

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.io.IOException
import android.support.v7.widget.LinearLayoutManager
import com.google.gson.GsonBuilder
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import java.util.logging.Logger.global


class MainActivity : AppCompatActivity() {

    val URL_MAIN = "http://api.themoviedb.org/3"
    val POPULAR_MOVIES = "/movie/popular"
    val TOP_RATED_MOVIES = "movie/top_rated"

    val URL_INDIVIDUAL_MOVIE = "http://image.tmdb.org/t/p/"
    val POSTER_SIZE = "w185"

    val ENTER_API_KEY = "?api_key="
    val API_KEY = "67bfdc871eabed5845200d39e64ed6e5"

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

        fetchJson()

        rv_poster_list.layoutManager = GridLayoutManager(this, 2)
    }

    fun fetchJson() {
        println("Attempting to Fetch JSON")

        val request = Request.Builder().url(URL_MAIN + POPULAR_MOVIES + ENTER_API_KEY + API_KEY).build()

        val client = OkHttpClient()
        client.newCall(request).enqueue(object: Callback {
            override fun onResponse(call: Call?, response: Response?) {
                val body = response?.body()?.string()
                println(body)

                val gson = GsonBuilder().create()

                val homeFeed = gson.fromJson(body, HomeFeed::class.java)

                runOnUiThread {
                    rv_poster_list.adapter = MovieAdapter(homeFeed)
                }
            }

            override fun onFailure(call: Call?, e: IOException?) {
                println("Failed to execute request")
            }
        })
    }
}

MovieAdapter.kt

package com.example.eijaz.popularmovies

import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.poster_list_item.view.*


class MovieAdapter(val homeFeed: HomeFeed) : RecyclerView.Adapter<CustomViewHolder>() {

    val URL_MAIN = "http://api.themoviedb.org/3"
    val POPULAR_MOVIES = "/movie/popular"
    val TOP_RATED_MOVIES = "movie/top_rated"

    val URL_INDIVIDUAL_MOVIE = "http://image.tmdb.org/t/p/"
    val POSTER_SIZE = "w185"

    val ENTER_API_KEY = "?api_key="
    val API_KEY = "67bfdc871eabed5845200d39e64ed6e5"

    override fun getItemCount(): Int {
        return homeFeed.results.count()
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CustomViewHolder {
        val layoutInflater = LayoutInflater.from(parent?.context)
        val cellForRow = layoutInflater.inflate(R.layout.poster_list_item, parent, false)
        return CustomViewHolder(cellForRow)
    }

    override fun onBindViewHolder(holder: CustomViewHolder?, position: Int) {

        val posterPath = homeFeed.results.get(position).poster_path
        val posterUrl = URL_INDIVIDUAL_MOVIE + POSTER_SIZE + posterPath

        val ivMoviePoster = holder?.view?.iv_movie_poster
        Picasso.with(holder?.view?.context).load(posterUrl).into(ivMoviePoster)

    }

}

class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {

    init {
        view.setOnClickListener {
            val intent = Intent(view.context, DetailActivity::class.java)

            view.context.startActivity(intent)
        }
    }

}

1 个答案:

答案 0 :(得分:0)

这不是因为onClickListener。这是因为您最初没有连接适配器。您需要做的是在MovieAdapter方法中附加一个空的适配器onCreate,然后在获取数据后,您可以在适配器中设置数据并调用notifydatasetchanged。类似rv_poster_list.adapter = MovieAdapter(Homefeed())之类的内容,然后在fetchJson()内加载数据后,您可以调用rv_poster_list.adapter.homefeed = <data>