简体   繁体   English

如何实现搜索视图模型并在 kotlin 中的 recyclerview 中显示它

[英]how to implement search viewmodel and show it in recyclerview in kotlin

I am developing tvshows app where I am implementing following logic user search tvshows and filtered result has to show in recyclerview but I want to implement filtering functionality in viewmodel我正在开发 tvshows 应用程序,我正在实现以下逻辑用户搜索 tvshows 和过滤结果必须显示在 recyclerview 中,但我想在 viewmodel 中实现过滤功能

how can I achieve that我怎样才能做到这一点

below interface class下面的接口类

interface ApiInterface {

    @GET("search/shows")
    suspend fun searchShows( @Query("q") query: String): Call<TvMazeResponse>

}

below TvRepository.kt在 TvRepository.kt 下面

class TvRepository(private val apiInterface: ApiInterface) {


suspend fun getShows() = apiInterface.searchShows("")

}

below adapter class下面的适配器类

class TvAdapter : RecyclerView.Adapter<TvAdapter.ViewHolder>(), Filterable {

    lateinit var tvMazeList: MutableList<TvMazeResponse>
    lateinit var filterResult: ArrayList<TvMazeResponse>


    override fun getItemCount(): Int =
        filterResult.size


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
        LayoutInflater.from(parent.context).inflate(
            R.layout.tv_item, parent,
            false
        )
    )

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


    fun addData(list: List<TvMazeResponse>) {
        tvMazeList = list as MutableList<TvMazeResponse>
        filterResult = tvMazeList as ArrayList<TvMazeResponse>
        notifyDataSetChanged()
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val charString = constraint?.toString() ?: ""
                if (charString.isEmpty()) filterResult =
                    tvMazeList as ArrayList<TvMazeResponse> else {
                    val filteredList = ArrayList<TvMazeResponse>()
                    tvMazeList
                        .filter {
                            (it.name.contains(constraint!!)) or
                                    (it.language.contains(constraint))

                        }
                        .forEach { filteredList.add(it) }
                    filterResult = filteredList

                }

                return FilterResults().apply { values = filterResult }
            }

            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                filterResult = if (results?.values == null)
                    ArrayList()
                else
                    results.values as ArrayList<TvMazeResponse>
                notifyDataSetChanged()
            }

        }
    }


    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        fun bind(result: TvMazeResponse) {
            with(itemView) {
                Picasso.get().load(result.image.medium).into(imageView)
            }
        }
    }


}

below Constants.kt下面是 Constants.kt

object Constants {
    const val BASE_URL = "https://api.tvmaze.com/"
}

below TvMazeResponse.kt在 TvMazeResponse.kt 下面

data class TvMazeResponse(
    @SerializedName("averageRuntime")
    val averageRuntime: Int,
    @SerializedName("dvdCountry")
    val dvdCountry: Any,
    @SerializedName("externals")
    val externals: Externals,
    @SerializedName("genres")
    val genres: List<String>,
    @SerializedName("id")
    val id: Int,
    @SerializedName("image")
    val image: Image,
    @SerializedName("language")
    val language: String,
    @SerializedName("_links")
    val links: Links,
    @SerializedName("name")
    val name: String,
    @SerializedName("network")
    val network: Network,
    @SerializedName("officialSite")
    val officialSite: String,
    @SerializedName("premiered")
    val premiered: String,
    @SerializedName("rating")
    val rating: Rating,
    @SerializedName("runtime")
    val runtime: Int,
    @SerializedName("schedule")
    val schedule: Schedule,
    @SerializedName("status")
    val status: String,
    @SerializedName("summary")
    val summary: String,
    @SerializedName("type")
    val type: String,
    @SerializedName("updated")
    val updated: Int,
    @SerializedName("url")
    val url: String,
    @SerializedName("webChannel")
    val webChannel: Any,
    @SerializedName("weight")
    val weight: Int
)

below TvViewModel.kt在 TvViewModel.kt 下面

class TvViewModel(apiInterface: ApiInterface) : ViewModel() {




}

I want to implement filter and search function in viewmodel how can I achieve that any help and tips greatly appreciated我想在视图模型中实现过滤器和搜索功能我怎样才能实现任何帮助和提示,非常感谢

In TvRepository change the getShows function to在 TvRepository 中,将 getShows 函数更改为

suspend fun getShows(searchString:String) = apiInterface.searchShows(searchString)

Then in the ViewModel change the constructor to get an instance of the TVRepository and call API as shown below然后在 ViewModel 中更改构造函数以获取 TVRepository 的实例并调用 API,如下所示

class TvViewModel( tvRepository: TvRepository) : ViewModel() {

 fun getShows(searchParameter:String){
   viewModelScope.launch(Dispatchers.IO){
     val response= tvRepository.getShows().awaitResponse()
     if(response.isSuccessful{
       //api success you can get result from response.body

     }
     else{
       //api failed
     }
   }
}



}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM