I want to convert HomeActivity into HomeFragment. As I want to use
changefragment(new HomeFragment());
What should I do? Please Suggest
I want to convert HomeActivity into HomeFragment. As I want to use
changefragment(new HomeFragment());
What should I do? Please Suggest
You have to change the way that the views are instantiated in the activities and shift it to the fragments. My personal preference is to create a new class file for the fragment and name it Fragment, eg. ListActivity
= ListFragment
.
Then inside the activity onCreate
method, you setContentView normally:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Then you need to create an instance of the fragment and inject it into the container that you've created inside your activity_list layout file:
ListFragment fragment = new ListFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_list_container, fragment)
.commit();
Treat the fragment similarly to the activity, except instead of using this
when referring to context, you use getActivity()
.
Here's an example of what your activity_list.xml
layout file could look like:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".ListActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_list_container"/>
</android.support.design.widget.CoordinatorLayout>