-->

Simple Fragments in Android

16 2019

1. Add the Framelayout Container in the layout where you want to show fragments.

<FrameLayout
    android:id="@+id/MainFrameContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

2. Import the following library.

import android.support.v4.app.FragmentTransaction;

3. Create the fragment transaction in Main Activity.

public class MainActivity extends AppCompatActivity
implements HomeFragment.OnFragmentInteractionListener {

    public HomeFragment Fragment_Home;
    FragmentTransaction fragmentTransaction;

    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       fragmentTransaction = getSupportFragmentManager().beginTransaction();
       Fragment_Home = new HomeFragment();
       fragmentTransaction.replace(R.id.MainFrameContainer,Fragment_Home);
       fragmentTransaction.addToBackStack(null);
       fragmentTransaction.commit();
   }
}

4. Create a fragment layout “fragment_home.xml” and corresponding java class “HomeFragment.java”.

Leave a Reply