用Kotlin實現簡單的自定義ActionSheetView

Kotlin 引言

Google IO 2017 宣布了 Kotlin 會成為 Android 官方開發語言。

Kotlin 是一個基于 JVM 的新的編程語言,由 JetBrains 開發。
Kotlin可以編譯成Java字節碼,也可以編譯成JavaScript,方便在沒有JVM的設備上運行。
JetBrains,作為目前廣受歡迎的Java IDE IntelliJ 的提供商,在 Apache 許可下已經開源其Kotlin 編程語言。
Kotlin已正式成為Android官方開發語言。

正文

今天我主要介紹的是使用Kotlin去寫一個簡單的自定義View,從而學習Kotlin語言的各種魅力。

Gradle引入

model中

apply plugin: 'kotlin-android'

android {
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.2-4'

工程中引入

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Kotlin代碼

常量:ActionSheetConstants.kt

/**
 * Created by zyao89 on 2017/5/24.
 * Contact me at 305161066@qq.com or zyao89@gmail.com
 * For more projects: https://github.com/zyao89
 * My Blog: http://zyao89.me
 */
const val DEFAULT_COLOR: Int = 0xFF_02_7B_FF.toInt()
const val DEFAULT_SHADE_COLOR: Int = 0x88_00_00_00.toInt()
const val DEFAULT_BTN_CANCEL_COLOR: Int = 0xFF_87_87_87.toInt()
const val DEFAULT_BTN_SELECT_COLOR: Int = 0xFF_3D_DD_B0.toInt()

代碼塊一: BaseActionSheetView.kt

/**
 * Created by zyao89 on 2017/5/24.
 * Contact me at 305161066@qq.com or zyao89@gmail.com
 * For more projects: https://github.com/zyao89
 * My Blog: http://zyao89.me
 */
abstract class BaseActionSheetView(val context: Context, val list: List<ActionSheetBtnInfo>, val rootView: ViewGroup = ((context as Activity).window.decorView as ViewGroup)) : View.OnClickListener, View.OnTouchListener {
    protected val mBtnViewList: LinkedList<TextView> = LinkedList()
    protected var mCustomContent: LinearLayout? = null
    protected var mBtnCancel: TextView? = null
    //POP總容器
    private var mFrameLayout: FrameLayout = FrameLayout(context)
            .apply {
                setBackgroundColor(DEFAULT_SHADE_COLOR)
            }
    private var mPopupWindow: PopupWindow = PopupWindow(this.initView()
            .apply {
                mCustomContent = findViewById(R.id.pop_layout) as LinearLayout
                setOnTouchListener(this@BaseActionSheetView)
            }, MATCH_PARENT, MATCH_PARENT, true)
            .apply {
                animationStyle = R.style.popwin_anim_style
                setOnDismissListener { this@BaseActionSheetView.dismiss() }
                inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
                softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
            }

    init {
        this.initBtn()
        this.initCancel()
    }

    protected abstract fun initView(): View
    protected abstract fun initBtn()
    protected abstract fun initCancel()

    override fun onClick(v: View?) {
        when (v) {
            mBtnCancel -> {

            }
            is TextView, is Button -> v.tag.takeIf { it is Int }?.let {
                val onClickListener = list[v.tag as Int].onClickListener
                onClickListener?.onClick(v)
            }
            else -> {

            }
        }
        mPopupWindow.dismiss()
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        val height: Int = mCustomContent?.top!!.toInt()
        val y: Int = event?.y!!.toInt()
        when (event.action) {
            MotionEvent.ACTION_UP -> {
                y.takeIf { it < height }.let {
                    println("y: $y")
                    println("height: $height")
                    mPopupWindow.dismiss()
                }
            }
        }
        return true
    }

    private fun dismiss() {
        rootView.removeView(mFrameLayout)
    }

    fun setCancelText(text: String) {
        this.mBtnCancel?.text = text
    }

    fun setCancelTextColor(color: Int) {
        this.mBtnCancel?.setTextColor(color)
    }

    fun setCancelTextSize(size: Float) {
        this.mBtnCancel?.setTextSize(TypedValue.COMPLEX_UNIT_SP, size)
    }

    fun hideCancel() {
        this.mBtnCancel?.visibility = View.GONE
    }

    fun show() {
        rootView.addView(mFrameLayout, MATCH_PARENT, MATCH_PARENT)
        mPopupWindow.showAtLocation(mFrameLayout, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
    }

    /**
     * 根據手機的分辨率從 dp 的單位 轉成為 px(像素)
     */
    protected fun dip2px(context: Context, dpValue: Float): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.resources.displayMetrics).toInt()
    }
}

代碼塊二:ActionSheetBtnInfo.kt

/**
 * Created by zyao89 on 2017/5/24.
 * Contact me at 305161066@qq.com or zyao89@gmail.com
 * For more projects: https://github.com/zyao89
 * My Blog: http://zyao89.me
 */
data class ActionSheetBtnInfo(var text: String, var textColor: Int = DEFAULT_COLOR, var backgroundResource: Int = R.drawable.custom_view_select_pop_selector_btn) : Serializable {
    companion object {
        //這里可以填寫單例
    }

    var onClickListener: View.OnClickListener? = null

    /**
     * 自定義get和set方法
     */
    var textSize: Float? = null
        get() = field
        set(value) {
            field = value
        }
}

代碼塊三:ActionSheetView.kt

/**
 * Created by zyao89 on 2017/5/24.
 * Contact me at 305161066@qq.com or zyao89@gmail.com
 * For more projects: https://github.com/zyao89
 * My Blog: http://zyao89.me
 */
class ActionSheetView(context: Context, list: List<ActionSheetBtnInfo>) : BaseActionSheetView(context, list) {

    override fun initView(): View {
        return View.inflate(context, R.layout.custom_view_select_pop, null)
    }

    override fun initBtn() {
        for ((index, btnInfo) in list.withIndex()) {
            TextView(context)
                    .apply {
                        tag = index
                        text = btnInfo.text
                        btnInfo.textSize?.let {
                            setTextSize(TypedValue.COMPLEX_UNIT_SP, it)
                        }
                        height = dip2px(context, 44.0f)
                        gravity = Gravity.CENTER
                        layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, dip2px(context, 44.0f))
                        setTextColor(btnInfo.textColor)
                        setBackgroundResource(btnInfo.backgroundResource)
                        setOnClickListener(this@ActionSheetView)
                    }
                    .also {
                        val layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                        layoutParams.topMargin = dip2px(context, 5.0f)
                        mCustomContent?.addView(it, index, layoutParams)
                    }
                    .let {
                        mBtnViewList.add(it)
                    }
        }
    }

    override fun initCancel() {
        mBtnCancel = TextView(context)
                .apply {
                    text = "Cancel"
                    height = dip2px(context, 44.0f)
                    gravity = Gravity.CENTER
                    layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, dip2px(context, 44.0f))
                    setTextColor(if (list.isEmpty()) DEFAULT_BTN_SELECT_COLOR else list[0].textColor)
                    setBackgroundResource(if (list.isEmpty()) R.drawable.custom_view_select_pop_selector_btn else list[0].backgroundResource)
                    setOnClickListener(this@ActionSheetView)
                }
                .apply {
                    val layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                    layoutParams.topMargin = dip2px(context, 15.0f)
                    layoutParams.bottomMargin = dip2px(context, 20.0f)
                    mCustomContent?.let {
                        mCustomContent?.addView(this@apply, it.childCount, layoutParams)
                    }
                }
    }
}

代碼塊四:ActionSheetListView.kt

/**
 * Created by zyao89 on 2017/5/24.
 * Contact me at 305161066@qq.com or zyao89@gmail.com
 * For more projects: https://github.com/zyao89
 * My Blog: http://zyao89.me
 */
class ActionSheetListView(context: Context, list: List<ActionSheetBtnInfo>) : BaseActionSheetView(context, list) {

    override fun initView(): View {
        return View.inflate(context, R.layout.custom_view_select_list_pop, null)
    }

    override fun initBtn() {
        for ((index, btnInfo) in list.withIndex()) {
            TextView(context)
                    .apply {
                        tag = index
                        text = btnInfo.text
                        btnInfo.textSize?.let {
                            setTextSize(TypedValue.COMPLEX_UNIT_SP, it)
                        }
                        height = dip2px(context, 44.0f)
                        gravity = Gravity.CENTER
                        layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, dip2px(context, 44.0f))
                        setTextColor(btnInfo.textColor)
                        setBackgroundResource(R.drawable.custom_view_select_list_pop_selector_btn)
                        setOnClickListener(this@ActionSheetListView)
                    }
                    .also {
                        val layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                        layoutParams.topMargin = 1
                        mCustomContent?.addView(it, index, layoutParams)
                    }
                    .let {
                        mBtnViewList.add(it)
                    }
        }
    }

    override fun initCancel() {
        mBtnCancel = TextView(context)
                .apply {
                    text = "Cancel"
                    height = dip2px(context, 44.0f)
                    gravity = Gravity.CENTER
                    layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, dip2px(context, 44.0f))
                    setTextColor(DEFAULT_BTN_CANCEL_COLOR)
                    setBackgroundResource(R.drawable.custom_view_select_list_pop_selector_btn)
                    setOnClickListener(this@ActionSheetListView)
                }
                .apply {
                    val layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                    layoutParams.topMargin = 1
                    layoutParams.bottomMargin = dip2px(context, 1.0f)
                    mCustomContent?.let {
                        mCustomContent?.addView(this@apply, it.childCount, layoutParams)
                    }
                }
    }
}

布局文件Layout

layout布局一:custom_view_select_pop.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/pop_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

layout布局二:custom_view_select_list_pop.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/pop_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

anim文件
ppwindow_show_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="300"
        android:fromXDelta="0"
        android:toXDelta="0"
        android:fromYDelta="200"
        android:toYDelta="0"
        />
    <alpha
        android:duration="300"
        android:fromAlpha="0"
        android:toAlpha="1"
        />
</set>

ppwindow_hide_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="200"
        android:fromXDelta="0"
        android:toXDelta="0"
        android:fromYDelta="0"
        android:toYDelta="200"
        />
    <alpha
        android:duration="200"
        android:fromAlpha="1"
        android:toAlpha="0"
        />
</set>

drawable文件
custom_view_select_list_pop_selector_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid android:color="#cccccccc"/>
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="@android:color/white"/>
        </shape>
    </item>
</selector>

custom_view_select_pop_selector_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid android:color="#cccccccc"/>
            <corners android:radius="10dp" />
        </shape>
    </item>
    <item  >
        <shape>
            <solid android:color="@android:color/white"/>
            <corners android:radius="10dp"/>
        </shape>
    </item>
</selector>

styles.xml

<resources>
    <style name="popwin_anim_style">
        <item name="android:windowEnterAnimation">@anim/ppwindow_show_anim</item>
        <item name="android:windowExitAnimation">@anim/ppwindow_hide_anim</item>
    </style>
</resources>

演示

ActionSheetListView.png
ActionSheetView.png

GitHub源碼:zyao89/ZActionSheetView


作者:Zyao89;轉載請保留此行,謝謝;

個人博客:https://zyao89.cn

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內容