Last active
July 20, 2018 09:31
-
-
Save mrkostua/39b39815ae82fe61cc3941bf1bc73364 to your computer and use it in GitHub Desktop.
Kotlin RecycleView.Adapter as Single adapter for project with many RecycleViews.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Example of usage | |
//No need for RxBinding or additonal interfaces to handel views clicks | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { | |
super.onCreate(savedInstanceState, persistentState) | |
setContentView(R.layout.activity_main) | |
initializeRecycleView(ArrayList()) | |
} | |
private fun initializeRecycleView(data: List<CourseDo>) { | |
val adapter = RecycleViewAdapter(data, R.layout.course_row_item, object : ViewHolderBinder<CourseDo> { | |
private lateinit var tvTitle: TextView | |
private lateinit var tvDescription: TextView | |
override fun initializeViews(view: View) = with(view) { | |
tvTitle = findViewById(R.id.tvCourseTitle) | |
tvTitle.setOnClickListener { | |
//TODO handle click | |
} | |
tvDescription = findViewById(R.id.tvCourseDescription) | |
view.setOnClickListener { | |
val item: Int = rvAllCourses.getChildLayoutPosition(it) | |
Toast.makeText(context, "Clicked item is $item ", Toast.LENGTH_LONG).show() | |
} | |
} | |
override fun bind(item: CourseDo) { | |
with(item) { | |
tvTitle.text = title | |
tvDescription.text = description | |
} | |
} | |
}) | |
rvAllCourses.layoutManager = LinearLayoutManager(this) | |
rvAllCourses.adapter = adapter | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RecycleViewAdapter<D>(private val data: List<D>, private val layoutRes: Int, private val binder: ViewHolderBinder<D>) | |
: RecyclerView.Adapter<RecycleViewAdapter<D>.ViewHolder>() { | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecycleViewAdapter<D>.ViewHolder { | |
return ViewHolder(LayoutInflater.from(parent.context).inflate(layoutRes, parent, false), binder) | |
} | |
override fun getItemCount() = data.size | |
override fun onBindViewHolder(holder: RecycleViewAdapter<D>.ViewHolder, position: Int) { | |
holder.bind(data[position]) | |
} | |
inner class ViewHolder(private val view: View, private val binder: ViewHolderBinder<D>) : RecyclerView.ViewHolder(view) { | |
init { | |
binder.initializeViews(this.view) | |
} | |
fun bind(item: D) { | |
binder.bind(item) | |
} | |
} | |
} | |
fun bind(item: D) { | |
binder.bind(item) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment