简体   繁体   中英

Styling issue when using FragmentScenario

When using FragmentScenario from androidx.fragment:fragment-testing to test fragment UI, not all styles are applied correctly.

As an example, there's very simple application that just presents fragment with following layout:

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>

with default theme generated by Android Studio (4.1.2) that looks like this when running the app:

在此处输入图像描述

doesn't look the same when run as a FragmentScenario test:

在此处输入图像描述

I can understand that ActionBar is not shown (as it is a part of host Activity not a Fragment ). But why Button is not styled correctly ...??

As others have commented FragmentScenario will launch your Fragment in a EmptyFragmentActivity (defined within the FragmentScenario class) by default this uses the R.style.FragmentScenarioEmptyFragmentActivityTheme .

To ensure our tests use the correct theme we supply our theme Theme_App to the themeResId param (as well as any Arguments) and it renders correctly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM