使用FragmentScenario时的样式问题

z4iuyo4d  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(103)

使用androidx.fragment:fragment-testing中的FragmentScenario测试片段UI时,并非所有样式都能正确应用。
例如,有一个非常简单的应用程序,它只显示具有以下布局的片段:
fragment_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Hello World!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Android Studio(4.1.2)生成的默认主题,运行应用时如下所示:

当作为FragmentScenario测试运行时,看起来不一样:

我可以理解ActionBar没有显示(因为它是主机Activity的一部分,而不是Fragment)。但是为什么Button的样式不正确...🤔??

xsuvu9jc

xsuvu9jc1#

正如其他人所评论的,FragmentScenario将在EmptyFragmentActivity(在FragmentScenario类中定义)中启动您的Fragment。默认情况下,这将使用R.style.FragmentScenarioEmptyFragmentActivityTheme
为了确保我们的测试使用正确的主题,我们将主题Theme_App提供给themeResId参数(以及任何Arguments),它将正确呈现。

val scenario: FragmentScenario<MyFragment> = launchFragmentInContainer(
            themeResId = style.Theme_App,
            fragmentArgs = args
        )

相关问题