[java] FragmentActivity to Fragment

I haven't found any question like this on here so I wanted to ask. Please keep in mind that I'm new to Fragments & FragmentActivity (not Android) and I don't really know how to work with them quite yet but I'm learning. My question is I want to know how to change from a FragmentActivity to a Fragment so I can incorporate it into my app seamlessly without any errors. The code I want to rid errors of is below

   public class Work extends Fragment implements     ActionBar.TabListener {  private ViewPager viewPager; private TabsPagerAdapter mAdapter; private ActionBar actionBar; // Tab titles private String[] tabs = { "Tattoos", "Piercings", "Social Networks" };  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.our_work);      // Initilization     viewPager = (ViewPager) findViewById(R.id.pager);     actionBar = getActionBar();     mAdapter = new TabsPagerAdapter(getSupportFragmentManager());      viewPager.setAdapter(mAdapter);     actionBar.setHomeButtonEnabled(false);     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);              // Adding Tabs     for (String tab_name : tabs) {         actionBar.addTab(actionBar.newTab().setText(tab_name)                 .setTabListener(this));     }      /**      * on swiping the viewpager make respective tab selected      * */     viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {          @Override         public void onPageSelected(int position) {             // on changing the page             // make respected tab selected             actionBar.setSelectedNavigationItem(position);         }          @Override         public void onPageScrolled(int arg0, float arg1, int arg2) {         }          @Override         public void onPageScrollStateChanged(int arg0) {         }     }); }  @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { }  @Override public void onTabSelected(Tab tab, FragmentTransaction ft) {     // on tab selected     // show respected fragment view     viewPager.setCurrentItem(tab.getPosition()); }  @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { }  } 

I've tried 3 different ways of doing this by rearranging the code but nothing works. Please help me with this!

EDIT I've tried it this way now

public class Work extends Fragment implements ActionBar.TabListener {  private ViewPager viewPager; private TabsPagerAdapter mAdapter; private ActionBar actionBar; private String[] tabs = { "Tattoos", "Piercings", "Social Networks" };  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState) { rootView       = inflater.inflate(R.layout.our_work, container, false);  // Initilization viewPager = (ViewPager) findViewById(R.id.pager); actionBar = getActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager());  viewPager.setAdapter(mAdapter); actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);          // Adding Tabs for (String tab_name : tabs) {     actionBar.addTab(actionBar.newTab().setText(tab_name)             .setTabListener(this)); }  /**  * on swiping the viewpager make respective tab selected  * */ viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {      @Override     public void onPageSelected(int position) {         // on changing the page         // make respected tab selected         actionBar.setSelectedNavigationItem(position);     }      @Override     public void onPageScrolled(int arg0, float arg1, int arg2) {     }      @Override     public void onPageScrollStateChanged(int arg0) {     } }); }  return rootView; }  @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { }  @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // on tab selected // show respected fragment view viewPager.setCurrentItem(tab.getPosition()); }  @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { }  } 

This question is related to java android android-fragments fragment

The answer is


first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to fragment

FragmentActivity to Fragment Handling back button in Android Navigation Component android.content.Context.getPackageName()' on a null object reference Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment How to move from one fragment to another fragment on click of an ImageView in Android? Android - save/restore fragment state Intent from Fragment to Activity Get the Application Context In Fragment In Android? Add Items to ListView - Android Using onBackPressed() in Android Fragments