【问题标题】:Why onLongclicklistener does no work in onBindviewholder with kotlin为什么 onLongclicklistener 在 kotlin 的 onBindviewholder 中不起作用
【发布时间】:2019-06-28 09:42:08
【问题描述】:

我已寻找解决此问题的方法,但找不到答案。 我可以让我的 onClickListener 在适配器的 onBindViewHolder 内工作(Kotlin),但 onLongClickListener(Kotlin)没有响应,即使代码没有显示错误

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

    val ingredientdisplay=displayItems[position]
    holder.setData(ingredientdisplay,position)
    runningTotal=runningTotal+holder.itemView.tvcost.text.toString().toDouble()
    println ("running total $runningTotal")

    val intent = Intent("message_from_displayadapter")
    intent.putExtra("runningtotal", runningTotal)
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent)   

    holder.itemView.setOnLongClickListener {view->
        println("longclick")
        true
    }

    holder.itemView.setOnClickListener {
        val intent = Intent(context, ChooseIngredientsActivity::class.java)
        ContextCompat.startActivity(context, intent, null)
    }
}

我只是尝试println 或运行Toast,但没有任何反应。

我不明白为什么?我们将不胜感激。

【问题讨论】:

  • 请不要使用println,它实际上不会将消息打印到Android的logcat,而只会打印到标准输出;而是使用 Android 提供的 Log 类将语句记录到 logcat,它支持指定一个标签,以便您更轻松地搜索您通过该标签记录的特定消息。
  • 您还应该使用加法赋值(又名+=)到您将变量分配给添加了双精度的变量的行。 (例如 runningTotal += /* value to add */ 而不是 runningTotal = runningTotal + /* value to add */)(查看 Kotlin 文档了解更多该语言支持的运算符:kotlinlang.org/docs/reference/…
  • Edric .谢谢你们两个有效的观点,但他们没有回答问题或影响代码的运行。

标签: android kotlin android-recyclerview onlongclicklistener


【解决方案1】:

首先不要将您的onClicklistiner 放入onBindViewHolder 这不是一个好习惯,使用像这样更新您的适配器类OnLongclicklistiner 工作正常

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.newsitemlist , 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.cardview.setOnClickListener {

            val i = Intent(context,NewsReaderActivity::class.java)
            i.putExtra("body",currentnews!!.body)
            i.putExtra("title",currentnews!!.title)
            context.startActivity(i)

        }

        itemView.cardview.setOnLongClickListener{
            Toast.makeText(context,"Long Clicked",Toast.LENGTH_SHORT).show()
            true
        }


        //the end of the init
    }

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

        }

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

  }

【讨论】:

  • 感谢您的回复。我已经按照你的建议做了,但仍然只有 onClicklistener 正在工作。 onLongClickListener 只是没有响应。
  • 编辑您的问题并发布整个适配器类
【解决方案2】:

我已将侦听器移至内部类,完整适配器的代码如下。仍然 onLongClicListener 没有响应。

类 RecipiesDisplayAdapter(val context:Context, val displayItems:List):RecyclerView.Adapter(){

var runningTotal:Double=0.00

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

}

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

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

    val ingredientdisplay=displayItems[position]
    holder.setData(ingredientdisplay,position)
    runningTotal=runningTotal+holder.itemView.tvcost.text.toString().toDouble()
    println ("running total $runningTotal")

    val intent = Intent("message_from_displayadapter")
    intent.putExtra("runningtotal", runningTotal)
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent)

}


inner class MyViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){

 private var  currentIngredientDisplay:IngredientDisplay?=null
 private var  currentPosition:Int=0


    init {

        itemView.setOnLongClickListener {
            Log.i ("clicked ", "longclick")
            context.showToast("longClicked")
             true
        }


        itemView.setOnClickListener {

            val intent = Intent(context, ChooseIngredientsActivity::class.java)
            ContextCompat.startActivity(context, intent, null)

        }

    }

   fun setData(ingredientdisplay: IngredientDisplay?, pos:Int){

       val fromrate=getfromdb(ingredientdisplay!!.unitPurchased)
       val torate =getfromdb(ingredientdisplay!!.unitPerRecipe)

       val minunitcost= ingredientdisplay!!.costPurchased/ingredientdisplay!!.quantityPurchased/fromrate
       val costperrecipe=minunitcost*ingredientdisplay!!.quantityPerRecipe*torate
       val s = String.format( "%.2f", costperrecipe);

       val pdu=ingredientdisplay!!.quantityPerRecipe.toString()+" "+ingredientdisplay!!.unitPerRecipe


       ingredientdisplay?.let {

           itemView.tvIngredientName.text = ingredientdisplay!!.ingredientName
           itemView.tvcost.text = s
           itemView.tvqty.text = pdu
       }
       this.currentPosition=pos
       this.currentIngredientDisplay=ingredientdisplay

   }

    fun getfromdb (unit:String) :Double{

        var sendback:String=""

        context.database.use {
            select("Units", "convertionrate")
                .`whereSimple`("unitname = ?", unit)

                .exec {


                    parseList(DoubleParser).forEach{

                        println("result $it")

                        val resu= it.toString()

                        sendback=resu
                    }
                }

        }

        return sendback.toDouble()
    }

}

}

我不知道为什么!

【讨论】:

    【解决方案3】:

    问题解决了。我犯了一个菜鸟的错误。我将所有 onclicklisteners 添加到我的适配器中。后来开始给他们添加onlongclicklisteners。信不信由你。我将它设置在错误的适配器中。为您的麻烦道歉,但您的回答有帮助。

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2011-06-07
      • 2022-12-03
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多