【问题标题】:RecyclerView SearchView giving wrong URL onClickRecyclerView SearchView 在点击时给出错误的 URL
【发布时间】:2020-07-31 01:25:11
【问题描述】:

我一直在努力在 RecyclerView 上获取 URL 的正确位置。我使用 FCM 获取数据并将其存储在 SharedPreference 上。我在我的 RecyclerView 中实现了一个 SearchView 来过滤特定的单词,它工作正常。

问题是当您搜索该词然后单击recyclerView 时,它会将您发送到原始recyclerView 的第一个位置的url,而不是过滤的那个。我试图改变我的 BindViewHolder 的位置,但它似乎不起作用。还要在 ViewHolder 中的 onClick 函数上更改位置,但不能以太,这可能是因为 onClick 函数需要一个 Int 并且它找到了我在 Notificaciones 上的内容 This is the error I get 当我在我的界面上将其更改为 Notificaciones 时,onClick 停止工作。

这是我的适配器

class NotifAdapter(private var mContext: Context, items:ArrayList<Notificaciones>, var listener: onClickListenerForAdapter): RecyclerView.Adapter<NotifAdapter.ViewHolder>(), Filterable {

var items: ArrayList<Notificaciones>?= null
var itemsFiltered: ArrayList<Notificaciones>?= null

init {
    this.items = items
    this.itemsFiltered = items

}


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotifAdapter.ViewHolder {
    val vista = LayoutInflater.from(mContext).inflate(R.layout.cv_notif, parent, false)
    val viewHolder = ViewHolder(vista,listener)

    return viewHolder
}

override fun getItemCount(): Int {
    return itemsFiltered?.count()!!
}

override fun onBindViewHolder(holder: NotifAdapter.ViewHolder, position: Int) {
    val item = itemsFiltered?.get(position)
    holder.title?.text = item?.title
    holder.body?.text = item?.body
    holder.fecha?.text = item?.fecha
    holder.img?.setImageResource(item?.img!!)


    //Animaciones para la imagen
    holder.img?.animation = AnimationUtils.loadAnimation(mContext,R.anim.aparecer_animacion)

    //Animación para el mensaje
    holder.mensaje?.animation = AnimationUtils.loadAnimation(mContext, R.anim.crecer_animacion)

}

inner class ViewHolder(vista:View, listener:onClickListenerForAdapter): RecyclerView.ViewHolder(vista), View.OnClickListener{
    var vista  = vista
    var title: TextView? = null
    var body: TextView? = null
    var fecha: TextView? = null
    var listener:onClickListenerForAdapter? = null
    var img: ImageView? = null
    var mensaje:RelativeLayout? = null
     var items: ArrayList<Notificaciones>?= null
     var itemsFiltered: ArrayList<Notificaciones>?= null


    init {
        title = vista.findViewById(R.id.tituloNotif)
        body = vista.findViewById(R.id.textNotif)
        fecha = vista.findViewById(R.id.fechaNotif)
        img = vista.findViewById(R.id.imgNotif)
        mensaje = vista.findViewById(R.id.contenido)
        this.listener = listener
        vista.setOnClickListener(this)
    }

    override fun onClick(v: View?) {

        val adapterPosition = itemsFiltered?.get(adapterPosition)
        this.listener?.onClick(v!!, adapterPosition)

    }
}

override fun getFilter(): Filter {
    return object : Filter() {
        override fun performFiltering(constraint: CharSequence): FilterResults {
            val Key = constraint.toString()
            itemsFiltered = if (Key.isEmpty()) {
                items
            } else {
                val lstFiltered = java.util.ArrayList<Notificaciones>()
                for (row in items!!) {
                    if (row.title.toLowerCase().contains(Key.toLowerCase()) || row.body.toLowerCase().contains(Key.toLowerCase())) {
                        lstFiltered.add(row)
                    }
                }
                lstFiltered
            }
            val filterResults = FilterResults()
            filterResults.values = itemsFiltered
            return filterResults
        }

        override fun publishResults(constraint: CharSequence, results: FilterResults) {
            itemsFiltered = results.values as java.util.ArrayList<Notificaciones>
            notifyDataSetChanged()
        }
    }

}}

这是我的 Notificaciones 课程

class Notificaciones(title: String, body: String, fecha: String, imagen: Int){

var title = ""
var body = ""
var fecha = ""
var img = 0
init {
    this.title = title
    this.body = body
    this.fecha = fecha
    this.img = imagen
}

}

这是我的 RecyclerView 的界面

interface onClickListenerForAdapter {
fun onClick(vista: View, index: Int)

}

这是我的活动课

class ventanaNotif : AppCompatActivity() {

val notifList = ArrayList<Notificaciones>()
var lista:RecyclerView? = null
lateinit var adaptador: NotifAdapter
var layoutManager: RecyclerView.LayoutManager? = null
lateinit var shared: SharedPreferences
private val COUNT_KEY = "Conteo"
var busqueda: EditText?= null

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

    //findViews
    lista = findViewById(R.id.rv_notif) //RecyclerView nuevo
    busqueda = findViewById(R.id.busqueda)//Busqueda de texto

    //Nuevo RecyclerView
    lista?.setHasFixedSize(true)
    layoutManager = LinearLayoutManager(this)
    lista?.layoutManager = layoutManager
    adaptador = NotifAdapter(this ,notifList, object:onClickListenerForAdapter{

            override fun onClick(vista: View, index: Int) {


                val url = notifList.get(index).fecha.toString()
                val i = Intent(Intent.ACTION_VIEW)
                i.data = Uri.parse(url)
                startActivity(i)
        }

    })
    lista?.adapter = adaptador


    //funciones
    notifData()


    butBorrar.setOnClickListener {
        shared.edit().clear().apply()
        adaptador.notifyItemRemoved(adaptador.itemCount)
    }

    //Metodo de busqueda por TextWatcher
    busqueda?.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            adaptador.filter.filter(s)
        }
        override fun afterTextChanged(s: Editable) {
        }
    })
}

override fun onBackPressed() {
    val intent = Intent(this, ventanaHome::class.java)
    startActivity(intent)
    finish()
    super.onBackPressed()
}

fun notifData() {

    shared = getSharedPreferences("Notificaciones", Context.MODE_PRIVATE)
    var count = shared.getInt(COUNT_KEY, 0)

    for ((x, valor) in (1..count).withIndex()) {
        notifList.add(
            Notificaciones(
                "${shared.getString("TituloData${valor}", "Todo bien")}",
                "${shared.getString("CuerpoData${valor}", "No hay más notificaciones")}",
                "${shared.getString("UrlData${valor}", "Sin URL ")}", R.drawable.ic_steren2)
        )

        adaptador.notifyItemInserted(adaptador.itemCount)
    }
}}

当我像这样改变我的界面时

interface onClickListenerForAdapter {

fun onClick(vista: View, notificaciones: Notificaciones)}

我的 Activity 上的 onClick 停止工作,因为缺少从 notifList 获取 fecha 的索引。

adaptador = NotifAdapter(this ,notifList, object:onClickListenerForAdapter{

        override fun onClick(vista: View, notificaciones: Notificaciones) {


            val url = notifList.get(index).fecha.toString()
            val i = Intent(Intent.ACTION_VIEW)
            i.data = Uri.parse(url)
            startActivity(i)}

我希望你能发现错误。任何帮助将不胜感激

谢谢你:)

【问题讨论】:

    标签: android kotlin android-recyclerview position searchview


    【解决方案1】:

    你的界面有这样的定义:

    interface onClickListenerForAdapter {
        fun onClick(vista: View, index: Int)
    }
    

    并且您没有将适配器位置作为第二个参数传递 - 您正在传递您从列表中获取的 Notificationes 对象:

    override fun onClick(v: View?) {
        val adapterPosition = itemsFiltered?.get(adapterPosition)
        this.listener?.onClick(v!!, adapterPosition)
    }
    

    因此,您需要将界面更改为:

    interface onClickListenerForAdapter {
        fun onClick(vista: View, notificationes: Notificaciones)
    }
    

    或将onClick 方法更改为:

    override fun onClick(v: View?) {
        this.listener?.onClick(v!!, adapterPosition)
    }
    

    而你现在在 onClick 方法中实际拥有的内容应该是这样命名的:

    override fun onClick(v: View?) {
        val notificationes = itemsFiltered?.get(adapterPosition)
        this.listener?.onClick(v!!, notificationes)
    }
    

    干杯!

    【讨论】:

    • 非常感谢,Mariusz。我已经这样做了,忘记解释 onClick 函数在我的 Activity 类中停止。查看
    【解决方案2】:

    这对我有帮助。

    1. 删除接口并在 onBindViewHolder 中使用 onClickListener。
     holder.vista.setOnClickListener{
                    if(url!= ""){
                        val i = Intent(Intent.ACTION_VIEW)
                        i.data = Uri.parse(url)
                        mContext.startActivity(i)
                    } else {
                        Toast.makeText(mContext,"No hay archivos adjuntos :)", Toast.LENGTH_SHORT).show()
                    }}
    

    希望这会对某人有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多