Kotlin for android學(xué)習(xí)十五(布局篇):多個(gè)頁面使用toolbar例子

前言

kotlin官網(wǎng)kotlin教程學(xué)習(xí)教程的筆記。
接口可以被用來從類中提取出相似行為的通用代碼。比如,創(chuàng)建一個(gè)接口用于處理app中的toolbar。多個(gè)activity在處理toolbar時(shí),會(huì)共享這些相似的代碼。

一、布局

1. toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="#ff212121"
    android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
   />

2. activity_main.xml

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar"
        />
</FrameLayout>

二、重寫Application

class App : Application() {
    companion object {
        private var INSTANCE: App? = null
        fun instance() = INSTANCE!!
    }

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
    }
}

三、創(chuàng)建ToolbarManager接口

interface ToolbarManager {
    val toolbar: Toolbar

    // 改變title
    var toolbarTitle: String
        get() = toolbar.title.toString()
        set(value) {
            toolbar.title = value
        }

    // 給所有的activity設(shè)置相同的菜單,甚至行為
    fun initToolbar() {
        toolbar.inflateMenu(R.menu.menu_main)
        toolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.action_setting -> App.instance().toast("setting")
                else -> App.instance().toast("other")
            }
            true
        }
    }

    // 顯示并指定上一步的導(dǎo)航動(dòng)作
    fun enableHomeAsUp(up: () -> Unit) {
        toolbar.navigationIcon = createUpDrawable()
        toolbar.setNavigationOnClickListener { up() }
    }

    fun createUpDrawable() = with(DrawerArrowDrawable(toolbar.context)) {
        progress = 1f
        this
    }

    // 滾動(dòng)時(shí)的toolbar動(dòng)畫
    fun attachToScroll(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0) {
                    toolbar.slideExit()
                } else toolbar.slideEnter()
            }
        })
    }
}

四、創(chuàng)建兩個(gè)用于view從屏幕中顯示或者消失動(dòng)畫的擴(kuò)展函數(shù)

fun View.slideExit() {
    if (translationY == 0f) {
        animate().translationY(-height.toFloat())
    }
}

fun View.slideEnter() {
    if (translationY < 0f) {
        animate().translationY(0f)
    }
}

五、在MainActivity中使用

1. mainActivity

class MainActivity : Activity(), ToolbarManager {
    override val toolbar by lazy {
        find<Toolbar>(R.id.toolbar)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recycler.layoutManager = LinearLayoutManager(this)
        initToolbar()
        attachToScroll(recycler)
        doAsync {
            var result: List<User> = listOf()
            database.use {
                result = select(UserContract.TABLE_NAME)
                        .parseList(classParser())
            }
            uiThread {
                recycler.adapter = MyAdapter(result) {
                   startActivity(intentFor<OtherActivity>(OtherActivity.ID to it.id,OtherActivity.NAME to it.name))
                }
                toolbarTitle = "數(shù)據(jù)庫數(shù)據(jù),共${result.size}條"
            }
        }
    }
}

2. adapter

class MyAdapter(var list: List<User>, private val click: (User) -> Unit) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    override fun onBindViewHolder(holder: MyAdapter.MyViewHolder?, position: Int) {
        with(list[position]) {
            holder?.item?.text = name
            holder?.item?.setOnClickListener {
                click(this)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyAdapter.MyViewHolder {
        return MyViewHolder(LayoutInflater.from(parent?.context).inflate(android.R.layout.simple_list_item_1, parent, false))
    }
    override fun getItemCount(): Int = list.size
    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var item = itemView.findViewById<TextView>(android.R.id.text1)
    }
}

六、OtherActivity

class OtherActivity : Activity(), ToolbarManager {
    override val toolbar by lazy {
        find<Toolbar>(R.id.toolbar)
    }

    companion object {
        val ID = "id"
        val NAME = "name"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other)

        initToolbar()
        toolbarTitle = intent.getStringExtra(NAME)
        enableHomeAsUp {
            onBackPressed()
        }
        txt.text = "MY ID IS ${intent.getLongExtra(ID,0)}"
    }
}

后記

也可以使用自定義委托實(shí)現(xiàn)Application單例化

class App : Application() {

    companion object {
        private var INSTANCE: App by DelegatesExt.notNullSingleValue()
        fun instance() = INSTANCE
    }

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
    }
}

object DelegatesExt {
    fun <T> notNullSingleValue() = NotNUllSingleValueVar<T>()
}

class NotNUllSingleValueVar<T> : ReadWriteProperty<Any?, T> {
    private var value: T? = null
    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return value ?: throw IllegalStateException("${property.name} not initialized")
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = if (this.value == null) value
        else throw IllegalStateException("${property.name} already initialized")
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容