android自定义视图findviewId为null并且不可见

我试图用我自己的自定义视图充满layout.xml文件。 我多次使用此视图,但有时在Android Studio中不会显示预览。 而当我通过’findViewById’得到这个自定义视图(实际上,我使用Kotlin所以我直接写Id),它总是返回null。 我读了很多关于“自定义视图findviewById返回null”的问题,直到现在我没有find答案。 我错了什么?

这是我的自定义类

class SubTitleBar(ctx:Context) : RelativeLayout(ctx) { private val mTitle:TextView private val mSideBtn:TextView constructor(ctx: Context, attrs: AttributeSet) : this(ctx) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SubTitleBar) setAttributeSet(typedArray) } constructor(ctx: Context, attrs: AttributeSet, defStyle:Int) : this(ctx, attrs) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SubTitleBar, defStyle, 0) setAttributeSet(typedArray) } init { val infService = Context.LAYOUT_INFLATER_SERVICE val inflater = ctx.getSystemService(infService) as LayoutInflater val view = inflater.inflate(R.layout.cv_subtitle,this,false) mTitle = view.findViewById(R.id.subtitle_title) mSideBtn = view.findViewById(R.id.subtitle_btn) addView(view) } private fun setAttributeSet(typedArray: TypedArray) { val titleText = typedArray.getString(R.styleable.SubTitleBar_title) mTitle.text = titleText val btnText = typedArray.getString(R.styleable.SubTitleBar_btnText) if (btnText!= null && btnText.isNotEmpty()) { mSideBtn.text = btnText } else { mSideBtn.visibility = TextView.GONE } val showDivider = typedArray.getBoolean(R.styleable.SubTitleBar_showDivider, false) if (showDivider) { subtitle_divider.visibility = View.VISIBLE } typedArray.recycle() } fun setTitle(title:String) { mTitle.text = title } fun setSideButtonClickListener(listener: (View) -> Unit) = mSideBtn.setOnClickListener(listener) } 

这是cv_subtitle.xml文件

       

在片段布局资源文件中,我使用这样的。

   

在片段(或活动)我尝试这样。

 val subTitle = my_apt_list_subtitle 

我也尝试,但不起作用。

 val subTitle = view.findViewById(R.id.my_apt_list_subtitle) 

尝试在cv_subtitle.xml中包含SubTitleBar