1. 程式人生 > >Android中Kotlin的學習(點選事件、跳轉、for迴圈、RecyclerView、回撥)

Android中Kotlin的學習(點選事件、跳轉、for迴圈、RecyclerView、回撥)

剛剛學習Kotlin,有什麼不對的地方請見諒。

首先屬性的宣告中有兩個很重要的關鍵字: var  和  val。

例如:

var a = "hello"
val b = "hello"
區別是什麼呢? var可多次分配; val只能一次初始化。

點選事件:

xml中View定義:

<android.support.v7.widget.AppCompatButton
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button 1"/>
有幾種實現方法,我就偷會兒懶,只寫最簡單的一種:
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button1.setOnClickListener { showToast("點選了按鈕") }
    }

fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
哈哈.... 程式碼中為什麼省略了 findViewById() 呢 ,  記得一定要在你的model下的build中加入,有的就不用加了, 沒有的就要手動加入

apply plugin:'kotlin-android-extensions' , 到時你在程式碼中輸入上面的 button1 時 , 就會自動帶入這個包 import kotlinx.android.synthetic.main.activity_second.*

頁面跳轉並攜帶資料,引用另一類中的屬性:

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra(SecondActivity::action.get(SecondActivity()), "傳遞正確")
startActivity(intent)

SecondActivity:

class SecondActivity : AppCompatActivity() {

  // val action = "com.secondActivity.intent" 也可以
    val action: String = "com.secondActivity.intent"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
	// 此處textView同上面button1一樣的
        textView.text = intent.getStringExtra(action)
    }

for迴圈:

例子:

val str = "Hello Kotlin !"
var array = arrayOf("3","d","x","gfd","w"," ","k","5","1","","h","4")

for (i in array) print(i) // 陣列遍歷                        結果:3dxgfdw k51h4
println()
for (i in array.reversed()) print(i) // 倒序                 結果:4h15k wgfdxd3
println()
for (i in 0..array.size-1) print(i) // .. 範圍               結果:01234567891011
println()
for (i in 2..2) print(i)        //                           結果:2
println()
for (i in array.size downTo 3) print(i)     //               結果:1211109876543
println()
for (i in array.size - 1 downTo 0 step 5) print(array[i]) // 結果:4kd
println()
for (i in str) print(i) // 字串遍歷                        結果:Hello Kotlin !
println()
for (i in 0..str.lastIndex) print(i)                 //      結果:012345678910111213
println()
for (i in 0..str.length-1) print(i)                   //     結果:012345678910111213
println()
RecyclerView :

activity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initRecyclerView()
    }

fun initRecyclerView() {
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        recyclerView.adapter = MainAdapter(this, array)
    }
adapter:

介面卡的結構如下,它自建立一些必須的方法:

注:構造方法直接就放在類名後面了。

class MainAdapter(var context: Context, var data: Array<String>) : RecyclerView.Adapter<MainAdapter.MyViewHolder>() {

    override fun getItemCount(): Int {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onBindViewHolder(p0: MyViewHolder?, p1: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onCreateViewHolder(p0: ViewGroup?, p1: Int): MyViewHolder {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }


    class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)
}
有些元素被標註為nullable。這是因為如果庫沒有適當的@Nullable和@NonNull標註,Kotlin就沒有方法知道null是否允許,這就要讓我們來決定了。
如果我們通過預設方式自建立方法了,它就會認為其值是nullable。
但是,進一步研究支援庫,我們就知道哪些值是為null,所以我們能夠刪除它。
class MainAdapter(var context: Context, var data: Array<String>) : RecyclerView.Adapter<MainAdapter.MyViewHolder>() {

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.title.text = "標題:"
        holder.content.text = data[position]
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
        return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.listitem_main, parent, false))
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var title: TextView = itemView.findViewById(R.id.tv_title) as TextView
        var content: TextView = itemView.findViewById(R.id.tv_content) as TextView
    }
}

之前說到kotlin可以不用findViewById() , 因此這裡也可以這樣寫:

class MainAdapter(var context: Context, var data: Array<String>) : RecyclerView.Adapter<MainAdapter.MyViewHolder>() {

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.itemView.tv_title.text = "標題:"
        holder.itemView.tv_content.text = data[position]
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
        return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.listitem_main, parent, false))
    }

    class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)
}
是不是感覺程式碼量縮短了很多。你再想想,item中有很多view,是不是就要繁瑣的findViewById()。而這裡就可以不用,就可以不用去做那些無聊的事情。

結果:



回撥 :

首先定義一個介面:

interface OnItemClickListener {

    fun onclick(v: View, position: Int)

}

然後:

adapter:

class MainAdapter(val context: Context, val data: Array<String>) : RecyclerView.Adapter<MainAdapter.MyViewHolder>() {

    private var onItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.itemView.tv_title.text = "標題:"
        holder.itemView.tv_content.text = data[position]
        if (onItemClickListener != null) {
            holder.itemView.tv_title.setOnClickListener { onItemClickListener?.onclick(holder.itemView.tv_title, position) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
        return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.listitem_main, parent, false))
    }

    class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)

}

activity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initRecyclerView()
    }

fun initRecyclerView() {
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        val mainAdapter = MainAdapter(this, array)
        recyclerView.adapter = mainAdapter
        mainAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onclick(v: View, position: Int) {
                Toast.makeText([email protected], position.toString(), Toast.LENGTH_SHORT).show()
            }
        })
    }



總結:看起來和用java開發是一樣的,重點是要學習kotlin的語法、關鍵字、符號等這些基本的東西還是要好好的去研究一下。