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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Android知识点总结

1-VIII--ViewPager的基本使用

1003
来自专栏向治洪

解决水平ListView在ScrollView中出现的滑动冲突

解决的问题有两个:  1)实现水平滑动的ListView。重写AdapterView,上代码:  Java代码   package com.liucanwen...

3239
来自专栏向治洪

android 实现倒影

首先,文章中出现的Gallery 已经不再适用,替代方法请看我的另一篇文章http://blog.csdn.net/xiangzhihong8/article...

2135
来自专栏非著名程序员

Android实现滑动刻度尺效果,选择身高体重和生日

刻度尺效果虽然看起来很美,我个人认为很不实用,即使再不实用,也有用的,鉴于群里成员对我的苦苦哀求,我就分享一个他用不到的,横屏滑动刻度尺,因为他需要竖屏的,哈哈...

22310
来自专栏吴小龙同學

Android更换主题

来自开源项目:https://github.com/lguipeng/Notes,其中有改变主题的功能,我做了部分修改,并应用到我的APP中。感谢lguipe...

3045
来自专栏向治洪

TableLayout和Viewpager实现切换

因为我是在之前的基础上写的,所以这个TableLayout和Viewpager实际上是写在Fragment上的。要写到Activity里其实也是一样的啦。 ...

18610
来自专栏Android干货园

Android 获取屏幕高宽度,密度,通知栏高度,截图等常用方法

版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/lyhhj/article/details/49...

1051
来自专栏非著名程序员

Android学习笔记(一)之仿正点闹钟时间齿轮滑动的效果

看到正点闹钟上的设置时间的滑动效果非常好看,自己就想做一个那样的,在网上就开始搜资料了,看到网上有的齿轮效果的代码非常多,也非常难懂,我就决定自己研究一下,现在...

20810
来自专栏向治洪

android自定义listview实现header悬浮框效果

之前在使用iOS时,看到过一种分组的View,每一组都有一个Header,在上下滑动的时候,会有一个悬浮的Header,这种体验觉得很不错,请看下图: ? ...

4876
来自专栏懒人开发

鸿洋AutoLayout代码分析(三):入口类分析

我们可以发现,只是做了name的判断, 如果是属性中的3中Layout, 会自动替换成 对应的AutoXXXLayout 如果不是,直接调用父类的 View...

812

扫码关注云+社区