我试图将一个 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/