Fragments
Fragments are self-contained UI components that can be combined to create a single activity. Fragments can be used to create flexible and responsive layouts that can adapt to different screen sizes and orientations.
Here's an example of how to create a simple fragment:
java
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
return view;
}
}
In the above example, we have defined a fragment called "MyFragment". In the onCreateView method, we inflate a layout called "fragment_layout" and return the view.
To add the fragment to an activity, use the following code:
scss
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
In the above example, we create a FragmentManager and FragmentTransaction objects, create an instance of the MyFragment class, and add it to the activity using the add method of the FragmentTransaction object.
No comments:
Post a Comment