I'm trying to get the clicked value from my list view from outside the ListView. When I click on my item, I want to fill a textView inside my fragment.
In the fragment, I have a searchView and the ListView.
this is my adapter :
class ListAdapterHoraire (context: Context, resource: Int, list: ArrayList<String>, private val arguments: Bundle?, private val forScol : Boolean) : ArrayAdapter<String>(context, resource, list) {
private val TAG = ListAdapterCustom::class.java.simpleName
var nameArret: String = ""
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = super.getView(position, convertView, parent)
val arret = view.findViewById<TextView>(R.id.arret)
val receivedBundle = arguments
arret.setOnClickListener {
val fragment = HorairePassage()
fragment.arguments = receivedBundle
nameArret = arret.text.toString()
Log.i(TAG, "${arret.text} clicked")
getArretCode(arret.text.toString(), fragment) //récupération du code arret + changement de fragment (en cascade)
}
if (position % 2 == 1) {
view.setBackgroundResource(R.color.colorWhite)
} else {
view.setBackgroundResource(R.color.grayBackground)
}
return view
}
Part of the fragment :
search.setOnQueryTextListener(object : android.support.v7.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(newText: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if(newText.length > 3){
loadingArretSearch.visibility = View.VISIBLE
getListeArrets(view, newText.trim(), resultArgument)
adapter = ListAdapterHoraire(view.context, R.layout.list_adapter, lignes, resultArgument, false)
listSearchView.adapter = adapter
adapter.filter.filter(newText.trim())
if(newText.trim() != ""){
listSearchView.visibility = View.VISIBLE
}else{
listSearchView.visibility = View.GONE
}
}else{
lignes.clear()
loadingArretSearch.visibility = View.GONE
listSearchView.visibility = View.GONE
}
return false
}
})
for a cases like this --> try to pass a callback into the adapter and the you can lunch any method from your activity and then you can do what you want from your activity .
class MyRecyclerViewAdapter(params , val itemClick: (Int) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
itemView.setOnClickListener( {itemClick(layoutPosition)} )
}
}
In your fragment or Activity
val myAdapter = MyRecyclerViewAdapter(params) { position ->
// do something
}
--> in your case
ListAdapterHoraire(view.context, R.layout.list_adapter, lignes, resultArgument, false){value->
// do something
}
class ListAdapterHoraire (context: Context, resource: Int, list: ArrayList<String>, private val arguments: Bundle?, private val forScol : Boolean,onItemClicked: (text: String) -> Unit) : ArrayAdapter<String>(context, resource, list) {
...
arret.setOnClickListener { onItemClicked(arret.text.toString()) }
...
}