Created
May 18, 2017 07:06
-
-
Save interchen/c55184b6b492b86b3c8a8a5d73de26b8 to your computer and use it in GitHub Desktop.
The way to use class reflection in Kotlin
This file contains hidden or 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
package com.homeking365.kotlindemo | |
import android.content.Intent | |
import android.os.Bundle | |
import android.support.v7.app.AppCompatActivity | |
import android.support.v7.widget.LinearLayoutManager | |
import android.support.v7.widget.RecyclerView | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import kotlinx.android.synthetic.main.activity_main.* | |
import kotlinx.android.synthetic.main.list_item_simple_row.view.* | |
import kotlin.reflect.KClass | |
class MainActivity : AppCompatActivity() { | |
internal val titles = listOf( | |
mapOf("title" to "KotlinActivity", "class" to KotlinActivity::class), | |
mapOf("title" to "JavaActivity", "class" to JavaActivity::class)) | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
recyclerView.adapter = SimpleAdapter() | |
recyclerView.layoutManager = LinearLayoutManager(baseContext) | |
} | |
inner class SimpleAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { | |
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { | |
val viewHolder = holder as SimpleViewHolder | |
viewHolder.bindData(titles[position]) | |
} | |
override fun getItemCount(): Int { | |
return titles.size | |
} | |
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { | |
val view = LayoutInflater.from(parent?.context).inflate(R.layout.list_item_simple_row, parent, false) | |
return SimpleViewHolder(view) | |
} | |
} | |
inner class SimpleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { | |
init { | |
itemView.setOnClickListener { | |
val clazz = titles[adapterPosition]["class"] as KClass<*> | |
val intent = Intent(this@MainActivity, clazz.java) | |
startActivity(intent) | |
} | |
} | |
fun bindData(data: Map<String, Any>) { | |
itemView.textView.text = data["title"].toString() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment