Android App Development | Fragments | Lecture#44 | Hive Learners
饾摉饾摶饾摦饾摦饾摻饾摬饾摲饾摪饾摷
Hello Hive Learners, I hope you all are well. yesterday we created a Tab Layout and in the Tab Layout, we add two Tan Items and use the ViewPager to show the two Fragments. Today we will use these two fragments and move of Blogs_Activity code to Blogs_Fragment. We will also move the design and delete the Blog_Activity java file and related XML file.
GitHub Link
Use this GitHub project to clone into your directory. The following lecture will constantly update it so you will never miss the latest code. Happy Coding!
What Should I Learn
- How to use Fragments
Assignment
- Use Fragments instead of Activity
Procedure
In Blog_Fragment.java I remove all the unnecessary code and return a view as shown here. We will use this view to bind the Tab Layouts items. There is an empty constructor of Blogs_Fragment and it is necessary too.
public class Blogs_Fragment extends Fragment {
public Blogs_Fragment() {
// Required empty public constructor
}
private ListView posts_lv;
ArrayList<MyList_POJO> myList_pojos;
MyAdapter customAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blogs, container, false);
return view;
}
}
Now I am moving all the java code from Blogs_Activity to Blogs_Fragment and we will solve the errors.
Add view at the start of findViewById, and we need to use requireContext() in place of this.
If we run the app we get an error as the layout file does contain the correct data. We need to move the code from activity_blogs to fragment_blogs.
In the welcome screen, we need to remove the blogs_card and the transfers_card in the code and from the XML.
The same we will do in the Transfers_Funds_Fragment. Move the Transfers_Activity code in it and also move the XML code and delete the Blogs_Activity, Transfers_Activity, and their XML files.
Now, let's run the app and check it the Fragments working properly or not.