首页 > 解决方案 > 片段显示在我的手机上,但不在 XML 预览中

问题描述

我有一个活动LoginActivity和一个片段GoogleSignInFragment。该应用程序的登录逻辑工作得很好,但唯一让我烦恼的是GoogleSignInFragment没有出现在activity_login.xml. 如果没有它出现,我将很难将我的代码移动到 Fragments,因为我不能再为活动设置样式了

这是所有相关代码...

LoginActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.sign_in_google, new GoogleSignInFragment())
                .commit();

}

activity_login.xml

<FrameLayout
    android:id="@+id/sign_in_google"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout="@layout/fragment_sign_in_google_button"/>

GoogleSignInFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_google_sign_in_button, container, false);

    return v;
}

fragment_google_sign_in_button.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    tools:context=".GoogleSignInFragment">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_google_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

</FrameLayout>

标签: javaandroidxml

解决方案


有时 Android Studio 无法加载预览,因此您可以尝试File选项中的Invalidate Cache / Restart选项。

为此,转到文件>单击无效缓存/重新启动


推荐阅读