Android Studio 3.2 预览版中导航预览不可用。

69

我对在Android Studio中展示的导航图感兴趣。但是,在我导入Google示例后,无法预览。

我使用的是Android Studio 3.2 Preview Canary 16版本。

输入图片说明

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:startDestination="@+id/launcher_home">

    <fragment
        android:id="@+id/launcher_home"
        android:name="com.android.samples.arch.componentsbasicsample.StartFragment"
        android:label="Home">

        <action
            android:id="@+id/end_action"
            app:destination="@id/end_dest" />

    </fragment>

    <fragment
        android:id="@+id/end_dest"
        android:name="com.android.samples.arch.componentsbasicsample.EndFragment"
        android:label="End"
        >

    </fragment>
</navigation>

2018年10月6日更新:

即使我重新构建项目,它也无法正常工作。但如果添加了新屏幕,则可以在预览模式下显示新屏幕。

在此输入图片描述

3个回答

235
你应该点击导航编辑器中的“文本”选项卡(导航图的xml文件),并添加以下内容:

你应该点击导航编辑器中的“文本”选项卡(导航图的xml文件),并添加:

tools:layout="@layout/layout_name"

目标元素内部。

应该像这样:

<fragment
    android:id="@+id/someFragment"
    android:name="com.freesoulapps.navigationtest.fragments.SomeFragment"
    android:label="Some Fragment"
    tools:layout="@layout/layout_name">
</fragment>

1
好的。这个解决方案可行。但我有一个关于这个语句的问题。如何使用默认片段布局而不是设计时布局? - Long Ranger
1
导航编辑器不知道您在片段的“onCreateView”方法中放置的布局。 - Alex
即使您在空白Activity中添加了Fragment,如果没有设置设计时属性,设计面板仍会在activity.xml中显示Fragment布局,这是不正确的。 - Long Ranger
我不明白,在哪里创建空白活动?在导航编辑器内吗? - Alex

20
有另一种方法可以在导航 XML 中进行预览。 首先,在您的 XML 片段中添加

tools:context="com.packagename.nameFragment"

我的布局示例

就是这样了

如果您进入导航文件,可以在选择和导航编辑器中看到预览

输入图像描述 输入图像描述

如果您查看代码,它是自动编写的

tools:layout="@layout/layout_name"

对我来说,在导航编辑器中添加片段之前先预览更加合理。 也许有一些方法可以自动将tools:context添加到布局中

自动完成不会为tools:context片段提供建议,仅为tools:context活动宿主提供建议,因此您需要编写片段的名称...如果有人有什么技巧

了解有关tools:context的更多信息: 进入链接描述


在使用ViewModel的片段时,它是否适用于您?因此,首先在xml中有<layout ...>,然后是主要的解压缩,例如ConstraintLayout?我最近进行了测试,但没有预览可用。 - mr.kostua

13

只需将 tools:layout="fragmentname" 添加到每个预览不可见的片段。 例如:

<navigation 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/startFragment">

    <fragment
        android:id="@+id/pickupFragment"
        android:name="com.example.cup_cake.PickupFragment"
        android:label="fragment_pickup"
        tools:layout="@layout/fragment_pickup" />

</navigation>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接