RecyclerView SearchView 给出错误的 URL onClick

RecyclerView SearchView giving wrong URL onClick

我一直在努力获得 URL 在 RecyclerView 上的正确位置。我使用 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()
        }
    }

}}

这是我的通知class

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)

}

这是我的Activityclass

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)}

我希望您能发现错误。非常感谢任何帮助

谢谢:)

您的接口定义如下:

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)
}

干杯!

这对我有帮助。

  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()
                }}

希望这对某人有所帮助