What can be the difference of using a fragment and frameLayout in android? Can both be used interchangeably?

纵饮孤独 提交于 2019-12-03 12:18:15

For showing a single Fragment immediately on the screen, yes, you can use fragment or FrameLayout interchangeably.

Single Fragment, Method 1

Showing the Fragment via the fragment tag would look like this in XML:

<fragment class="com.example.ExampleFragment"
        android:id="@+id/details" android:layout_weight="1"
        android:layout_width="0px" android:layout_height="match_parent" />

Single Fragment, Method 2

Showing the Fragment via FrameLayout would look like this in XML:

<FrameLayout android:id="@+id/details" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent" />

Followed by Java code like this:

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.details, newFragment);
transaction.addToBackStack(null);
transaction.commit();

Multiple Fragments

Method 2 then supports changing what fragment you are showing later by running more Java code to change what Fragment is there afterwards:

Fragment secondFragment = new SecondExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.details, secondFragment);
transaction.addToBackStack(null);
transaction.commit();

So FrameLayout gives you the extra ability to do that over using the fragment tag.

A framelayout, Relative View and a few others represents a view in android and is extended from viewgroup.

A Fragment is a an an Object that is used to represent a portion of a user interface and is usually hosted in an activity.

A fragment has a viewgroup which you can assign an XML layout. In the XML you can specify a viewgroup which can be a framelayout if you wish to represent the layout of the viewgroup within the fragment.

Fragments and framelayouts cannot be used interchangeably.

Having said that, you can create a Android application without the use of fragments, and just use viewgroups.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!