使用Kotlin为你的APP自定义一个统一的标题栏

这篇文章只是对《为你的APP自定义一个统一的标题栏》这篇文章的Kotlin重写



package com.yongxing.QianJR.widgets

import android.content.Context
import android.os.Build
import android.support.annotation.AttrRes
import android.support.annotation.DrawableRes
import android.text.TextUtils
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

import com.yongxing.QianJR.R
import com.yongxing.QianJR.utils.DensityUtil
import com.yongxing.QianJR.utils.StateBarUtil

/**
 * Created by xiaolei on 2017/5/10.
 */

class ContextTitle @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr)
{
    private var ViewWidth: Int = 0
    private var ViewHeight: Int = 0
    private var leftTextVisible = View.VISIBLE
    private var leftText: CharSequence = ""
    private var leftTextSize = 14f
    private var leftTextColor = 0xff000000.toInt()
    private var leftImage = R.mipmap.ic_launcher
    private var leftImageVisible = View.VISIBLE
    private var titleText: CharSequence = ""
    private var titleTextSize = 14f
    private var titleTextColor = 0xff000000.toInt()
    private var titleVisible = View.VISIBLE
    private var titleRightImg = -1
    private var rightImage = R.mipmap.ic_launcher
    private var rightImageVisible = View.VISIBLE
    private var rightTextVisible = View.VISIBLE
    private var rightText: CharSequence = ""
    private var rightTextSize = 14f
    private var rightTextColor = 0xff000000.toInt()
    private var titleScrllo = false
    /* -------------初始化UI----------------- */

    val leftImgView by lazy {
        ImageView(context).apply {
            layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT).apply {

            }
            setImageResource(leftImage)
            setPadding(DensityUtil.dip2px(context, 15f), 0, DensityUtil.dip2px(context, 15f), 0)
            scaleType = ImageView.ScaleType.CENTER_INSIDE
            visibility = leftImageVisible
        }
    }

    private val leftTextview by lazy {
        TextView(context).apply {
            layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT).apply {
                setMargins(DensityUtil.dip2px(context, 8f), DensityUtil.dip2px(context, 0f), DensityUtil.dip2px(context, -8f), DensityUtil.dip2px(context, 0f))
            }
            text = leftText
            gravity = Gravity.CENTER
            setTextColor(leftTextColor)
            setTextSize(TypedValue.COMPLEX_UNIT_SP, leftTextSize)
            visibility = leftTextVisible
        }
    }
    private val titleTextview by lazy {
        TitleTextView(context).apply {
            layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER)
            layoutParams = layoutParams
            text = titleText
            maxEms = 8
            //android:ellipsize="end"
            ellipsize = TextUtils.TruncateAt.END
            gravity = Gravity.CENTER
            setTextSize(TypedValue.COMPLEX_UNIT_SP, titleTextSize)
            visibility = titleVisible
            setTextColor(titleTextColor)
            setSingleLine()
            if (titleScrllo)
            {
                ellipsize = TextUtils.TruncateAt.MARQUEE
                marqueeRepeatLimit = -1
                isFocusable = true
                setHorizontallyScrolling(true)
                isFocusableInTouchMode = true
            }
            if (titleRightImg > -1)
            {
                val drawable = context.resources.getDrawable(titleRightImg)
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                setCompoundDrawables(null, null, drawable, null)
                compoundDrawablePadding = DensityUtil.dip2px(context, 5f)
            }
        }
    }
    private val rightTextview by lazy {
        TextView(context).apply {
            layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT).apply {
                setMargins(DensityUtil.dip2px(context, -8f), DensityUtil.dip2px(context, 0f), DensityUtil.dip2px(context, 8f), DensityUtil.dip2px(context, 0f))
            }
            text = rightText
            gravity = Gravity.CENTER
            setTextColor(rightTextColor)
            visibility = rightTextVisible
            setTextSize(TypedValue.COMPLEX_UNIT_SP, rightTextSize)
        }
    }
    val rightImgView by lazy {
        ImageView(context).apply {
            layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT)
            setImageResource(rightImage)
            setPadding(DensityUtil.dip2px(context, 15f), 0, DensityUtil.dip2px(context, 15f), 0)
            visibility = rightImageVisible
            scaleType = ImageView.ScaleType.CENTER_INSIDE
        }
    }


    private val linearLayout by lazy {
        LinearLayout(context).apply {
            layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            orientation = LinearLayout.HORIZONTAL
            gravity = Gravity.CENTER_VERTICAL
        }
    }
    private val lineView by lazy {
        View(context).apply {
            layoutParams = LinearLayout.LayoutParams(DensityUtil.dip2px(context, 0f), DensityUtil.dip2px(context, 1f), 1f)
        }
    }

    init
    {
        val array = getContext().obtainStyledAttributes(attrs, R.styleable.ContextTitle)
        leftTextVisible = if (array.getBoolean(R.styleable.ContextTitle_leftTextVisible, false)) View.VISIBLE else View.GONE
        leftText = array.getText(R.styleable.ContextTitle_leftText) ?: "Left"
        leftTextSize = array.getInt(R.styleable.ContextTitle_leftTextSize, 14).toFloat()
        leftTextColor = array.getColor(R.styleable.ContextTitle_leftTextColor, 0xff000000.toInt())

        leftImageVisible = if (array.getBoolean(R.styleable.ContextTitle_leftImgVisible, false)) View.VISIBLE else View.GONE
        leftImage = array.getResourceId(R.styleable.ContextTitle_leftImg, R.mipmap.ic_launcher)

        titleText = array.getText(R.styleable.ContextTitle_titleText) ?: "Title"
        titleTextSize = array.getInt(R.styleable.ContextTitle_titleTextSize, 14).toFloat()
        titleTextColor = array.getColor(R.styleable.ContextTitle_titleTextColor, 0xff000000.toInt())
        titleVisible = if (array.getBoolean(R.styleable.ContextTitle_titleVisible, true)) View.VISIBLE else View.GONE
        titleRightImg = array.getResourceId(R.styleable.ContextTitle_titleRightImg, -1)

        rightImageVisible = if (array.getBoolean(R.styleable.ContextTitle_rightImgVisible, false)) View.VISIBLE else View.GONE
        rightImage = array.getResourceId(R.styleable.ContextTitle_rightImg, R.mipmap.ic_launcher)

        rightTextVisible = if (array.getBoolean(R.styleable.ContextTitle_rightTextVisible, false)) View.VISIBLE else View.GONE
        rightText = array.getText(R.styleable.ContextTitle_rightText) ?: "Right"
        rightTextSize = array.getInt(R.styleable.ContextTitle_rightTextSize, 14).toFloat()
        rightTextColor = array.getColor(R.styleable.ContextTitle_rightTextColor, 0xff000000.toInt())

        titleScrllo = array.getBoolean(R.styleable.ContextTitle_titleScrllo, false)

        array.recycle()
        InitUI()
    }

    private fun InitUI()
    {
        /* --------组合在一起---------- */
        linearLayout.addView(leftImgView)
        linearLayout.addView(leftTextview)
        this.addView(titleTextview)
        linearLayout.addView(lineView)
        linearLayout.addView(rightTextview)
        linearLayout.addView(rightImgView)
        this.addView(linearLayout)
        // 这里判断版本号是多少,并且根据版本号的不同,设置控件的高度,以及PaddingTop+信号栏的高度。
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener{
            override fun onGlobalLayout()
            {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                {
                    val layoutparams:ViewGroup.LayoutParams = this@ContextTitle.layoutParams
                    layoutparams.height = layoutparams.height + StateBarUtil.getStateBarHeigh(context)
                    this@ContextTitle.layoutParams = layoutparams
                    this@ContextTitle.setPadding(
                            this@ContextTitle.paddingLeft,
                            this@ContextTitle.paddingTop + StateBarUtil.getStateBarHeigh(context) ,
                            this@ContextTitle.paddingRight,
                            this@ContextTitle.paddingBottom)
                }
            }
        })
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
    {
        // 父容器传过来的宽度的值
        ViewWidth = View.MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight
        // 父容器传过来的高度的值
        ViewHeight = View.MeasureSpec.getSize(heightMeasureSpec) - paddingLeft - paddingRight

        if (titleScrllo)
        {
            val layoutParams = titleTextview.layoutParams
            layoutParams.width = ViewWidth * 4 / 9
            titleTextview.layoutParams = layoutParams
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }


    fun setLeftTextVisible(leftTextVisible: Int)
    {
        this.leftTextVisible = leftTextVisible
    }

    fun setLeftText(leftText: CharSequence)
    {
        this.leftText = leftText
    }

    /**
     * 默认单位SP

     * @param leftTextSize
     */
    fun setLeftTextSize(leftTextSize: Float?)
    {
        this.leftTextSize = leftTextSize!!
    }

    fun setLeftTextColor(leftTextColor: Int)
    {
        this.leftTextColor = leftTextColor
    }

    fun setLeftImage(leftImage: Int)
    {
        this.leftImage = leftImage
    }

    fun setLeftImageVisible(leftImageVisible: Int)
    {
        this.leftImageVisible = leftImageVisible
    }

    fun setTitleText(titleText: CharSequence)
    {
        this.titleText = titleText
        titleTextview.text = titleText
    }

    /**
     * 默认单位SP

     * @param titleTextSize
     */
    fun setTitleTextSize(titleTextSize: Float)
    {
        this.titleTextSize = titleTextSize
    }

    fun setTitleTextColor(titleTextColor: Int)
    {
        this.titleTextColor = titleTextColor
    }

    fun setTitleVisible(titleVisible: Int)
    {
        this.titleVisible = titleVisible
    }

    fun setRightImage(rightImage: Int)
    {
        this.rightImage = rightImage
    }

    fun setRightImageVisible(rightImageVisible: Int)
    {
        this.rightImageVisible = rightImageVisible
    }

    fun setRightTextVisible(rightTextVisible: Int)
    {
        this.rightTextVisible = rightTextVisible
    }

    fun setRightText(rightText: CharSequence)
    {
        this.rightText = rightText
    }

    /**
     * 默认单位SP

     * @param rightTextSize
     */
    fun setRightTextSize(rightTextSize: Float)
    {
        this.rightTextSize = rightTextSize
    }

    fun setRightTextColor(rightTextColor: Int)
    {
        this.rightTextColor = rightTextColor
    }
    
    fun setOnLeftImageClick(listener: View.OnClickListener) {
        leftImgView.setOnClickListener(listener)
    }
    
    fun setOnLeftTextClick(listener: View.OnClickListener)
    {
        leftTextview.setOnClickListener(listener)
    }

    fun setOnTitleClick(listener: View.OnClickListener)
    {
        titleTextview.setOnClickListener(listener)
    }

    fun setOnRightTextClick(listener: View.OnClickListener)
    {
        rightTextview.setOnClickListener(listener)
    }

    fun setOnRightImageClick(listener: View.OnClickListener)
    {
        rightImgView.setOnClickListener(listener)
    }

    fun setTitleRightImg(@DrawableRes titleRightImg: Int)
    {
        this.titleRightImg = titleRightImg
        if (titleRightImg > -1)
        {
            val rightDrawable = context.resources.getDrawable(titleRightImg)
            rightDrawable.setBounds(0, 0, rightDrawable.minimumWidth, rightDrawable.minimumHeight)
            titleTextview.setCompoundDrawables(null, null, rightDrawable, null)
            titleTextview.compoundDrawablePadding = DensityUtil.dip2px(context, 5f)
        }
    }

    /**
     * 获取标题文字

     * @return
     */
    fun getTitleText(): String
    {
        return titleTextview.text.toString()
    }

    fun setLeftTextTag(tag: Any)
    {
        leftTextview.tag = tag
    }

    fun <T> getLeftTextTag(): T
    {
        return leftTextview.tag as T
    }

    fun setLeftImgTag(tag: Any?)
    {
        leftImgView.tag = tag
    }

    fun <T> getLeftImgTag(): T
    {
        return leftImgView.tag as T
    }

    fun setTitleTextTag(tag: Any?)
    {
        titleTextview.tag = tag
    }

    fun <T> getTitleTextTag(): T
    {
        return titleTextview.tag as T
    }

    fun setRightTextTag(tag: Any)
    {
        rightTextview.tag = tag
    }

    fun <T> getRightTextTag(): T
    {
        return rightTextview.tag as T
    }

    fun setRightImgTag(tag: Any)
    {
        rightImgView.tag = tag
    }

    fun <T> getRightImgTag(): T
    {
        return rightImgView.tag as T
    }
}

class TitleTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : TextView(context, attrs, defStyleAttr)
{
    override fun isFocused(): Boolean
    {
        return true
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,686评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,668评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,160评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,736评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,847评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,043评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,129评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,872评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,318评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,645评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,777评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,861评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,589评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,687评论 2 351

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,857评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,066评论 4 62
  • 然而,人生并不像你想象中的那么残忍,当然也根本不是你所看到的那般风平浪静。我居然拥有了终生难忘的朋友,而这些朋友却...
    芳草兮阅读 581评论 9 9
  • 歌单来下载了又删,来来去去,反复折腾。在知道了宗次郎后,发现自己原来喜欢的是单纯的音乐。填了词反倒觉得失了真。昨日...
    天空v分阅读 171评论 0 0
  • 我遇见了猫在潜水,却没有遇见你 我遇见了狗在攀岩,却没有遇见你 我遇见夏天飘雪,却没有遇见你 我遇见冬天刮台风,却...
    北方的南方姑娘阅读 369评论 0 6