java - Activity 启动时的默认 fragment

标签 java android

我试图将一个 fragment 加载为 Activity 的默认 View ,但我只是看到一个空白屏幕和巨大的内存泄漏。

Activity 文件onCreate方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);

    if (savedInstanceState == null) {
        FragmentManager fragmentManager = getFragmentManager();
        int fragmentTransaction = fragmentManager.beginTransaction()
                .add(R.id.login_screen_fragment, new FragmentLogin())
                .commit();
    }
}

Activity 的 XML:

<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="match_parent"
    tools:context=".LoginActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/login_screen_fragment"
        class="com.test.project.FragmentLogin"
    />

    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/forgotten_password_fragment"
        class="com.test.project.FragmentForgottenPassword"
    />
</FrameLayout>

和 Fragment 类(相关部分):

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_login, container, false);
    final Activity activity = getActivity();

    ... code ...

    return view;
}

我按照某人早些时候从另一个问题提出的教程中的说明进行操作,但我一定是做错了一些可怕的事情。有什么想法吗?

最佳答案

xml文件

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/changeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
</FrameLayout>

您的 Activity

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 setContentView(R.layout.activity_login);

if (savedInstanceState == null) {
    FragmentLogin f1= new FragmentLogin();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.changeFragment, f1);
    fragmentTransaction.commit();

   }
}

关于java - Activity 启动时的默认 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200832/

相关文章:

java - 在 Java 中对对象使用运算符

java - 解开注释以撤消错误的 Eclipse 格式

android - 使用命令行导出已签名的应用程序包

android - 如何为按钮选择器设置不同的主题?

java - 如何将助记符放在角色的第二个实例(Java-Swing)下?

java - 我如何知道应用程序是使用java链接到wifi还是以太网?

java - 如何解决使用 for 循环打印表格的 Java 问题?

android - 去除android进度条中的进度条背景

java - 多个词不被搜索,不占用空间

java - 如何在 Android Studio 中修复 "Failed to resolve: com.google.gson:gson:2.8.5"