I have the layout for the activity:
<fragment
android:name="com.myapp.fragment1"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment1" />
<fragment
android:name="com.myapp.listfragment1"
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
The first fragment (fragment1) extends Fragment, whilst the second fragment extends ListFragment. I don't have a layout for the listfragment.
The activity code is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
}
An exception is thrown on setContentView:
Error inflating class fragment
The ListFragment code is:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyListAdapter(getActivity(), prices));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setDivider(null);
}
What is the correct way to have multiple fragments in an activity?
You can do it by using
SectionsPagerAdapter
(Swipe View) or byNavigationDrawer
(Navigation drawer). I have used swipe view for one of my applications. Here is the codes.MainActivity.java
FriendsFragment.java
activity_main.xml
fragment_main.xml
fragment_friends.xml
This is just a sample code of my project. You can use your own code for java or xml. Here i tried to show how to call the fragments in your
MainActivity
using swipe view. Hope it helps.