The code of activity_fragment.xml:
<?xml version="1.0" encoding="utf-8" ?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
The code of CrimeListActivity.java
package com.sinory.criminalintent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
public class CrimeListActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CrimeListActivity", "create");
}
}
The code of SingleFragmentActivity.java
package com.sinory.criminalintent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (null == fragment) {
fragment = new CrimeListFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
Just started to learn Android. Why Fragment fragment = fm.findFragmentById(R.id.fragmentContainer) is null? Please help me.
First, you don't need to check if the fragment is null because when an activity destroys all the fragment will also be destroyed. So in activity onCreate there will be no fragment and you need to add it each time the activity recreates.
Second don't use findFragmentById. You only use this method when you define your fragment inside your xml file. Now that you dynamically adding your fragment you need to specify a string tag and then use that tag to find the fragment.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().add(R.id.fragmentContainer, fragment,"TagName").commit();
}
if you need to find your fragment simply use this code
Fragment fragment = fm.findFragmentByTag("TagName");
Update on January 9, 2019
As of 2018, you can simply use Google Navigation library to navigate between the pages (fragments) in the app. It will handle all the transactions and makes it a lot easier and cleaner to do the navigation. check it out here
https://developer.android.com/topic/libraries/architecture/navigation/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With