簡體   English   中英

在自定義視圖中找不到片段的ID(...)的視圖

[英]No view found for id (…) for fragment inside Custom View

我創建接受片段的自定義視圖。 因此,以后我的自定義視圖具有動態內容( Fragment )。 但是添加片段時出現以下錯誤。

原因:java.lang.IllegalArgumentException:找不到片段SampleFragment {470c924#0 id = 0x7f080058}的ID 0x7f080058(android.amanah.com.amanah:id / flContent)的視圖

這是我的自定義視圖:

class AmBottomSheet(context: Context, attributeSet: AttributeSet?) : ConstraintLayout(context, attributeSet) {
    private val state = State()

    init {
        LayoutInflater.from(context)
                .inflate(R.layout.layout_bottom_sheet, this, true)
    }

    fun bind(newState: State.() -> Unit) {
        state.apply(newState)
        render(state)
    }

    private fun render(state: State) {
        tvTitle.text = state.title
        if (state.subTitle != null) {
            tvSubTitle.text = state.subTitle
        } else {
            tvSubTitle.visibility = GONE
        }

        ivClose.setOnClickListener {
            state.closeClickListener?.invoke(it)
        }

        attachContentFragment()
    }

    private fun attachContentFragment() {
        val transaction = state.supportFragmentManager?.beginTransaction()
        transaction?.replace(R.id.flContent, state.layoutContent)
        transaction?.commit()
    }

    class State {
        var title: String? = null
        var subTitle: String? = null
        var closeClickListener: (View?.() -> Unit)? = null
        var supportFragmentManager: FragmentManager? = null
        var layoutContent: Fragment? = null
    }
}

我這樣稱呼我的自定義視圖:

...
bottomSheetView.bind {
            title = "Informasi"
            subTitle = "We can even add some listeners to the BottomSheet and for example do something when the dialog is dismissed"
            closeClickListener = {
                bottomSheetDialog.dismiss()
            }
            supportFragmentManager = getSupportFragmentManager()
            layoutContent = SampleFragment.newInstance()
        }
...

和我的XML作為片段容器在我的自定義視圖( layout_bottom_sheet.xml )布局中,如下所示:

...
<FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/standard_margin_x2"
        android:background="@color/colorSlate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvSubTitle"
        app:layout_constraintVertical_bias="0.0" />
...

為什么我的自定義視圖找不到flContent

對話框與窗口管理器分開顯示,因此該對話框未包含在活動的視圖層中。 因此找不到您的flContent。

建議您使用BottomSheepDialogFragment並將片段替換為childFragmentManager。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM