Kotlin for android学习十五(布局篇):多个页面

2017-11-23  本文已影响228人  crossroads

前言

kotlin官网kotlin教程学习教程的笔记。
接口可以被用来从类中提取出相似行为的通用代码。比如,创建一个接口用于处理app中的toolbar。多个activity在处理toolbar时,会共享这些相似的代码。

一、布局

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
    }
}

三、创建ToolbarManager接口

interface ToolbarManager {
    val toolbar: Toolbar

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

    // 给所有的activity设置相同的菜单,甚至行为
    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
        }
    }

    // 显示并指定上一步的导航动作
    fun enableHomeAsUp(up: () -> Unit) {
        toolbar.navigationIcon = createUpDrawable()
        toolbar.setNavigationOnClickListener { up() }
    }

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

    // 滚动时的toolbar动画
    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()
            }
        })
    }
}

四、创建两个用于view从屏幕中显示或者消失动画的扩展函数

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 = "数据库数据,共${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)}"
    }
}

后记

也可以使用自定义委托实现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")
    }
}
上一篇 下一篇

猜你喜欢

热点阅读