获取recyclerview适配器中的单击项

时间:2019-06-28 08:19:27

标签: android kotlin android-recyclerview

我想用Kotlin创建一个Android应用。在此应用程序中,我还使用swagger将所有Web服务获取到一个文件中。 我要创建一个接口,说明如下:

  

包含所有类别列表的RecyclerView水平   来自Web服务 apiMobileProductCategoriesGetAllPost 。   之后,当我单击哪个类别时,RecyclerView(Grid)   出现包含按类别ID的所有产品。

我想知道当我单击项目时如何获得类别ID,以及如何在活动中使用它 以下是RecyclerView类别适配器:

 class CategoryAdapter(private val categories: Array<ProductCategoryData>) :
    RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {

    private var onItemClickListener: OnItemClickListener? = null

    override fun onClick(v: View?) {
        if (v != null) {
            onItemClickListener?.onItemClick(v, ProductCategoryData())
        }
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

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

    override fun getItemCount() = categories.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemCategory: ProductCategoryData = categories[position]

        holder.categoryId.text = itemCategory.id.toString()

        println(holder.categoryId.text)
        println(itemCategory.name?.get("En").toString())
        holder.categoryName.text = itemCategory.name?.get("En").toString()
        println(itemCategory.id)
        if (itemCategory.logo != null) {
            Picasso.get()
                .load("..../T/${itemCategory.logo}")
                .into(holder.categoryImage, object : com.squareup.picasso.Callback {
                    override fun onError(e: Exception?) {
                        holder.categoryImage.setImageResource(R.drawable.homecraftdefault)
                    }

                    override fun onSuccess() {
                        Picasso.get().load("....T/${itemCategory.logo}")
                            .into(holder.categoryImage)
                    }

                })
            holder.itemView.setOnClickListener {
                onItemClickListener?.onItemClick(holder.itemView,itemCategory)
            }
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
        val categoryName: TextView = itemView.categoryName
        val categoryImage: ImageView = itemView.categoryImage
        val categoryId: TextView = itemView.categoryId
        override fun onClick(v: View?) {
            if (v != null) {
                onItemClickListener?.onItemClick(v, ProductCategoryData())
            }
        }

    }

    interface OnItemClickListener {
        fun onItemClick(view : View, viewModel:ProductCategoryData)
    }

}

以下代码是相对于活动的:

class CategoryByProduct : AppCompatActivity(), CategoryAdapter.OnItemClickListener {

    override fun onItemClick(view: View, viewModel: ProductCategoryData) {
        var params =  "CategoryProductID";"5cc057458c4d9823743736d2"
        println(viewModel.id)
        val products = mobileApi!!.apiMobileProductsGetAllPost(params, 0, 50, "", "")
        recyclerViewProductByCategory.apply {
            recyclerViewProductByCategory.layoutManager = GridLayoutManager(this@CategoryByProduct, 2)
            recyclerViewProductByCategory.adapter = ProductAdapter(products)
        }    }

    var mobileApi: MobileApi? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.list_product_by_category)
        mobileApi = MobileApi()
        val params = HashMap<String, String>()
        GlobalScope.launch(Dispatchers.IO) {

            val categories = mobileApi!!.apiMobileProductCategoriesGetAllPost(params, 0, 50, "", "")
            withContext(Dispatchers.Main) {
                recyclerViewCategories.apply {
                    recyclerViewCategories.layoutManager =
                        LinearLayoutManager(this@CategoryByProduct, OrientationHelper.HORIZONTAL, false)
                    recyclerViewCategories.adapter = CategoryAdapter(categories)
                }
            }
        }



    }


    }

4 个答案:

答案 0 :(得分:0)

您可以通过调用adapterPosition来获得类别在视图支架中的位置,并由此可以从您提供给构造函数中的适配器的列表中获得类别(categories [adapterPosition])

答案 1 :(得分:0)

您的情况非常简单。请尝试以下操作:-

holder.tv_broadcast_title.text=broadList[position].name

其中 broadlist 是我在适配器本身中创建的数组列表。在此列表中,json数据是从api存储的。

internal var broadList = ArrayList<Model>()

.name 是用于从json数据中获取名称的密钥的名称。

holder.categoryName.text = itemCategory.name?.get("En").toString()

在您的情况下,请执行以下操作:-

itemCategory[position].name

答案 2 :(得分:0)

首先,不要将onclick放在onBindViewHolder中,这不是一个好习惯,在那之后,我认为您需要获得该类别的ID,我将给您一个简单的例子在所有的适配器类中

class NewsAdapter (val context: Context, private val arrayList: ArrayList <NewsModel>):
RecyclerView.Adapter <NewsAdapter.Holder> () {

companion object {
   // val TAG: String = OperationAdapter::class.java.simpleName
}

override fun onCreateViewHolder (parent: ViewGroup, viewType: Int): Holder {
    return Holder (LayoutInflater.from (parent.context ).inflate (R.layout.newslist , parent, false))
}

override fun getItemCount (): Int = arrayList. size

override fun onBindViewHolder (holder: Holder, position: Int) {

    val mynews = arrayList[position]
    holder.setData(mynews , position)

}

inner class Holder (itemView: View): RecyclerView.ViewHolder (itemView) {
    private var currentnews: NewsModel? = null
    private var currentPosition: Int = 0


    init {
        //The click listener

        itemView.newscardview.setOnClickListener {

            //do it here
            Toast.makeText(this,currentnews!!.id,Toast.LENGTH_SHORT).show()

        }
        //the end of the init
    }

    //getting data from model and bind it into View
    fun setData(news: NewsModel?, position: Int) {
        news?.let {
            itemView.newsid.text = news.id
            itemView.newstitle.text = news.title
            itemView.body.text = news.body
            itemView.txtdate.text = news.ndate

        }

        this.currentnews = news
        this.currentPosition = position
        }
      }

   }

在此示例中,当您单击ID时,您会收到新闻newscardview,我希望了解它

在您的活动中

将此代码放入onCreate

//set up the recycleview
mRecyclerView.setHasFixedSize (true)
mRecyclerView. layoutManager = LinearLayoutManager(this)

mRecyclerView是我的RecycleView

还可以在任何需要的地方调用您的Adapter类

//adapter
      val adapter = NewsAdapter (this,arrayList)
                    adapter.notifyDataSetChanged()
                    mRecyclerView.adapter = adapter

答案 3 :(得分:0)

要从适配器到活动获取数据,可以在适配器中或全局创建接口,并可以从活动中在适配器的构造函数中传递该接口并使用该接口获取数据。我给你举个例子。

interface ProductCategoryListner {
        fun getProductCategory(viewModel:ProductCategoryData)
    }

不在适配器的构造函数中添加此接口。

class CategoryAdapter(private val categories: Array<ProductCategoryData>,private val productCategoryListner: ProductCategoryListner):
    RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {

现在,您可以使用它在单击视图时在活动中传递数据。

productCategoryListner.getProductCategory(categories[adapterPosition])