【问题标题】:ViewStub inflation of ConstraintLayoutConstraintLayout 的 ViewStub 膨胀
【发布时间】:2021-09-03 08:05:57
【问题描述】:

我想利用ViewStub 来选择性地显示部分 UI。当我的膨胀项目的根是ConstraintLayout 时,它不会呈现。

但如果该根是MaterialCardView,那么它会按预期显示。

<!-- my_fragment.xml -->

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragmentRootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ViewStub
        android:id="@+id/fragmentViewStub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inflatedId="@+id/fragmentViewStub"
        android:layout="@layout/item"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<!-- item.xml -->

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/itemRootLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/itemLabel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/itemLabelText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
/* MyFragment.kt */

@AndroidEntryPoint
class MyFragment : Fragment(R.layout.my_fragment) {
    private val viewModel: MyViewModel by viewModels()

    private val viewBinding: MyFragmentBinding by viewLifecycleLazy {
        MyFragmentBinding.bind(requireView())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding.fragmentViewStub.inflate()
    }
}

我尝试了matching the ViewStub's id/inflatedId attributes 和programmatically setting dimensions/constraints,但都没有解决问题。

让这些部分协同工作我忽略了什么?

【问题讨论】:

    标签: android android-constraintlayout android-viewbinding viewstub


    【解决方案1】:

    忘记更新我的回答/监督。这在这两种情况下一直都按预期工作。

    夜间模式已启用,MaterialCardView 的行为在其卡片和内容之间具有自动对比。同时,当ConstraintLayout 反转其主题时,标签似乎丢失但确实存在,作为白色背景上的白色文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      相关资源
      最近更新 更多