今天就跟大家聊聊有關(guān)Android中怎么自定義頂部導(dǎo)航欄,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
具體代碼如下所示:
class HeaderBar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { //重寫(xiě)構(gòu)造方法 在java里面 我們一般是重寫(xiě)三個(gè)構(gòu)造方法//在kotlin中 我們可以使用@JvmOverloads constructor( // context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 // )后面的兩個(gè)參數(shù) 我們不傳的可以使用的是默認(rèn)值//定義一些變量private var isShowback = true private var titleText: String? = null private var rightText: String? = null //初始化 在init方法中 初始化布局 設(shè)置style init { //自定義屬性val typedArray = context.obtainStyledAttributes(attrs, R.styleable.HeaderBar) //取出在布局中定義的屬性isShowback = typedArray.getBoolean(R.styleable.HeaderBar_isShowBack, true) titleText = typedArray.getString(R.styleable.HeaderBar_titleText) rightText = typedArray.getString(R.styleable.HeaderBar_rightText) initView() typedArray.recycle() } //初始化控件的方法private fun initView() { //填充布局View.inflate(context, R.layout.layout_header_bar, this) mLeftIv.visibility = if (isShowback) View.VISIBLE else View.INVISIBLE titleText?.let { mTitleTv.text = it } rightText?.let { mRightTv.text = it mRightTv.visibility = View.VISIBLE } mLeftIv.onClick { if (context is Activity) (context as Activity).finish() } } fun getRightView(): TextView { return mRightTv } }
看完上述內(nèi)容,你們對(duì)Android中怎么自定義頂部導(dǎo)航欄有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。