I'm creating tabs dynamically with names and their corresponding id's I'm getting from a web API:
private fun getCategories() {
val url = "http://192.168.1.45/companyweb/get_categories"
val rq = Volley.newRequestQueue(this)
val jar = JsonArrayRequest(Request.Method.GET,url,null,Response.Listener { response ->
for (x in 0..response.length()-1) {
val category = Category(response.getJSONObject(x).getString("id"), response.getJSONObject(x).getString("name"))
categoryList.add(category)
val newTab = navigationTabs.newTab()
newTab.text = categoryList[x].name.toString()
navigationTabs.addTab(newTab)
}
}, Response.ErrorListener { error -> Log.d("HAVERI", error.toString()) })
rq.add(jar)
}
Once one of the tab is selected by the user, I would like to have a way to know to which category it corresponds. But the only thing I can get is its R.id such as:
com.google.android.material.tabs.TabLayout$Tab@90eb7ca
I'm using the navigation tabs listener:
navigationTabs.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {
override fun onTabReselected(p0: TabLayout.Tab?) {
}
override fun onTabUnselected(p0: TabLayout.Tab?) {
}
override fun onTabSelected(p0: TabLayout.Tab?) {
Log.d("TAG", "tab selected is " + p0.toString())
}
})
Is there a way to "mark" each added tab with an index, or another custom identifier, so I can recognize it later when it's selected. Using p0 in the listener isn't helpful.
You can attach the web id as tag. TabLayout.Tab
has a function setTag(Object).
Let's assume you pass in the web id as a String
value, then inside the functions of the TabLayout.OnTabSelectedListener
you can retrieve the tag by calling
val tag = p0.getTag() as String