簡體   English   中英

在 RecyclerView Item 上實現點擊監聽器 android

[英]Implement Click Listener On RecyclerView Item android

我已經為我的項目的 recyclerview 編寫了以下代碼。 我想在這個 recyclerview 的一個項目上實現 clicklistener。 你能指導我在我的代碼中找到問題嗎?

fragment_home.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="match_parent"
    android:background="@color/colorWhite"
    tools:context=".view.ui.HomeFragment">

    <include
        android:id="@+id/toolbarHome"
        layout="@layout/layout_toolbar" />

    <androidx.appcompat.widget.SearchView
        android:id="@+id/svSearchCountry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/_15sdp"
        android:layout_marginTop="@dimen/_15sdp"
        android:layout_marginEnd="@dimen/_15sdp"
        android:background="@drawable/layout_rectangle_edittext"
        android:textCursorDrawable="@null"
        app:iconifiedByDefault="false"
        app:layout_constraintTop_toBottomOf="@id/toolbarHome"
        app:queryBackground="@null"
        app:queryHint="Search Country" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvCountries"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="@dimen/_5sdp"
        android:layout_marginTop="@dimen/_15sdp"
        android:layout_marginEnd="@dimen/_5sdp"
        android:layout_marginBottom="@dimen/_5sdp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/svSearchCountry" />

</androidx.constraintlayout.widget.ConstraintLayout>

layout_country_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"
    android:layout_width="match_parent"
    android:id="@+id/countryItemParent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/ivCountry"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:padding="@dimen/_5sdp"
        android:layout_marginTop="@dimen/_5sdp"
        android:src="@drawable/kenya"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvCountryName"
        style="@style/CustomTextViewMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kenya"
        android:textColor="@color/colorText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ivCountry" />

</androidx.constraintlayout.widget.ConstraintLayout>

HomeFragment.kt

class HomeFragment : Fragment() {
    private lateinit var listener: CountriesAdapter.CountriesAdapterListener
    private lateinit var countriesAdapter: CountriesAdapter
    lateinit var toolbar: Toolbar
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        toolbar = view.findViewById(R.id.toolbar) as Toolbar
        setupUI()
        setupListeners()
        setupRecyclerView()

    }

    private fun setupListeners() {
        listener = object : CountriesAdapter.CountriesAdapterListener {
            override fun onClickedItem() {
                Log.d("onItemClickedCalled","Working")
                startActivity(Intent(requireActivity(), HomeActivity::class.java))

            }
        }

        svSearchCountry.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                countriesAdapter.filter.filter(newText)
                return false
            }
        })
    }

    private fun setupRecyclerView() {
        countriesAdapter =
            CountriesAdapter(
                listener,
                CountriesModel.countriesList as ArrayList<CountriesModel>
            )

        rvCountries.apply {
            layoutManager = GridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false)
            adapter = countriesAdapter
        }
    }

    private fun setupUI() {
        toolbar.title = "Home"
        val searchIcon = svSearchCountry.findViewById<ImageView>(R.id.search_mag_icon)
        searchIcon.setColorFilter(R.color.colorPrimary)
        val cancelIcon = svSearchCountry.findViewById<ImageView>(R.id.search_close_btn)
        cancelIcon.setColorFilter(R.color.colorText)
        val textView = svSearchCountry.findViewById<TextView>(R.id.search_src_text)
        textView.setTextColor(ContextCompat.getColor(activity as MainActivity, R.color.colorText))
    }
}

國家適配器.kt

class CountriesAdapter(
    private val listener: CountriesAdapterListener, var countriesList: ArrayList<CountriesModel>
) : RecyclerView.Adapter<CountriesAdapter.CountriesViewHolder>(), Filterable {

    var countryFilterList = ArrayList<CountriesModel>()
    init {
        countryFilterList = countriesList
    }

    interface CountriesAdapterListener {
        fun onClickedItem()
    }

    inner class CountriesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivCountryImage: ImageView = itemView.findViewById(R.id.ivCountry)
        val tvCountryTitle: TextView = itemView.findViewById(R.id.tvCountryName)
        val countryItemParent: ConstraintLayout = itemView.findViewById(R.id.countryItemParent)
    }

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

    override fun onBindViewHolder(holder: CountriesViewHolder, position: Int) {
        val countryItem = countryFilterList[position]
        Glide.with(holder.ivCountryImage.context).load(countryItem.imageURI)
            .into(holder.ivCountryImage)
        holder.tvCountryTitle.text = countryItem.title
        if (position%4==0){
            holder.itemView.visibility = View.INVISIBLE
        }
        holder.countryItemParent.setOnClickListener {
            listener.onClickedItem()
        }
    }

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

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val charSearch = constraint.toString()
                countryFilterList = if (charSearch.isEmpty()) {
                    countriesList
                } else {
                    val resultList = ArrayList<CountriesModel>()
                    for (row in countriesList) {
                        if (row.title.toLowerCase(Locale.ROOT)
                                .contains(charSearch.toLowerCase(Locale.ROOT))
                        ) {
                            resultList.add(row)
                        }
                    }
                    resultList
                }
                val filterResults = FilterResults()
                filterResults.values = countryFilterList
                return filterResults
            }

            @Suppress("UNCHECKED_CAST")
            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                countryFilterList = results?.values as ArrayList<CountriesModel>
                notifyDataSetChanged()
            }

        }
    }
}

請幫幫我,我被困在這里,不知道如何解決這個問題。

改變這個

holder.countryItemParent.setOnClickListener {
        listener.onClickedItem()
    }

有了這個

holder.itemView.setOnClickListener {
        listener.onClickedItem()
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM