一、問題
最近在自定view時候,遇到一個問題,view本身沒有錯誤,app運行起來界面也很正常,但在xml編寫引入自定view時,導致整個布局不能預覽
下面是我寫的代碼
class CustomTitleBarView (context: Context?, attrs: AttributeSet?) :
RelativeLayout(context, attrs, 0), LifecycleEventObserver {
private val layoutBack: RelativeLayout by lazy { findViewById<RelativeLayout>(R.id.layout_back) }
private val ivBack: ImageView by lazy { findViewById<ImageView>(R.id.iv_back) }
private val ivHeat: ImageView by lazy { findViewById<ImageView>(R.id.iv_heat) }
private val tvHeart: TextView by lazy { findViewById<TextView>(R.id.tv_heart) }
private val ivGold: ImageView by lazy { findViewById<ImageView>(R.id.iv_gold) }
private val tvGold: TextView by lazy { findViewById<TextView>(R.id.tv_gold) }
private val ivHome: ImageView by lazy { findViewById<ImageView>(R.id.iv_home) }
//點擊個人信息
var clickHomeInfoListener: () -> Unit = {
}
//點擊返回
var clickBackListener: () -> Unit ={
}
init {
LayoutInflater.from(context).inflate(R.layout.custom_title_bar, this)
val typedArray = context?.obtainStyledAttributes(attrs, R.styleable.CustomTitleBarView)
val leftDrawable = typedArray?.getDrawable(R.styleable.CustomTitleBarView_bar_left_drawable)
val rightDrawable = typedArray?.getDrawable(R.styleable.CustomTitleBarView_bar_right_drawable)
typedArray?.recycle()
if (leftDrawable != null){
ivBack.setImageDrawable(leftDrawable)
layoutBack.visibility = View.VISIBLE
}else{
layoutBack.visibility = View.GONE
}
if (rightDrawable != null){
ivHome.setImageDrawable(rightDrawable)
ivHome.visibility = View.VISIBLE
}else{
ivHome.visibility = View.GONE
}
refreshData()
clickListener()
TitleBarHelper.putView(this.hashCode(),this)
(context as AppCompatActivity).lifecycle.addObserver(this)
}
private fun clickListener(){
ivHome.setOnClickListener {
UserInfoActivity.startAction(context as Activity)
}
layoutBack.setOnClickListener {
(context as Activity).finish()
}
}
/**
* 動態(tài)設置用戶紅心和金幣
*/
fun setGoldData(heart: String?,gold: String?){
if (heart == null || gold == null){
return
}
GoldConfig.gold = gold
GoldConfig.heart = heart
refreshData()
}
fun refreshData(){
tvHeart.text = GoldConfig.heart
tvGold.text = GoldConfig.gold
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when(event){
Lifecycle.Event.ON_DESTROY ->{
TitleBarHelper.removeView(this.hashCode())
}
else -> {
}
}
}
}
二、原因
具體是下面這個方法在init初始化調用,導致不能在xml里面預覽,但本身代碼可以運行,不會出錯。網上查閱資料,是這部分邏輯需要設備支持(俺很懵),在xml中就無法預覽。
(context as AppCompatActivity).lifecycle.addObserver(this)
三、解決方法
解決也簡單,使用isInEditMode()做下判斷,如果是預覽,直接不執(zhí)行
if (!isInEditMode){
(context as AppCompatActivity).lifecycle.addObserver(this)
}