Android recyclerview item focus selection on dpad navigation
The main activity layout file with RecyclerView, activity_main.xml
The layout file for list item in the recyclerview, the focusable has to set to true, and the background is set to a selector drawable. list_item.xml
The background selector drawable, this will make the focused list item to display black background. item_selector.xml
MainActivity.kt
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val topics = listOf("Education","Finance","Government","Entertainment","Technology","Math","Biology","Physics","Chemistry","Space","Sports","Music","Animal","Countries","Weather","Politics","Traffic","Poverty","Social Media","Internet","Housing") val linearLayoutManager = LinearLayoutManager(this) val listAdapter = ItemListAdapter(topics) recycler_view.setHasFixedSize(true) recycler_view.layoutManager = linearLayoutManager recycler_view.adapter = listAdapter } }
The adapter, ItemListAdapter.kt
import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast class ItemListAdapter(private val itemList: List) : RecyclerView.Adapter () { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false) return ViewHolder(layoutView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.tvTopic.text = itemList[position] } override fun getItemCount() = itemList.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { var tvTopic: TextView init { itemView.setOnClickListener(this) tvTopic = itemView.findViewById (R.id.topic) as TextView } override fun onClick(view: View) { Toast.makeText(view.context, "Clicked Position = " + adapterPosition, Toast.LENGTH_SHORT).show() } } }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts