Add fragments to your app.
Create a new class for our Fragment:
public class AppFragment extends Fragment { public AppFragment() { // Empty constructor } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Essential View rootView = inflater.inflate(R.layout.our_fragment, container, false); // Use a custom layout file (see below) ImageView imageView = rootView.findViewById(R.id.ourImageView); // Here we find a View within the layout imageView.setImageResource(R.drawable.anImage); // And allocate an image to it return rootView; } }Our layout file for the Fragment, our_fragment.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/ourImageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:contentDescription="An Image" tools:srcCompat="@drawable/anImage" /> // Placeholder image </LinearLayout>Create an instance of our Fragment in the Activity and use FragmentManager to add it to the layout for the Activity:
AppFragment aFragment = new AppFragment(); // New instance of our custom Fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .add(R.id.fragment_container, aFragment) // Adds the new fragment to an element of the Activity layout (see below) .commit();Our layout file for the Activity, activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <ScrollView 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="com.example.android.app.MainActivity"> <LinearLayout android:id="@+id/main_activity_linear_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <FrameLayout android:id="@+id/fragment_container" // View that will contain the Fragment android:layout_width="match_parent" android:layout_height="180dp" android:scaleType="centerInside"/> </LinearLayout> </ScrollView>
