简体   繁体   中英

Are Android Fragments View or ViewGroup

As the question reads, Fragments in android are View or ViewGroup. Can anyone explain

Here is the onCreateView method of Fragment from docs

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

The container parameter passed to onCreateView() is the parent ViewGroup (from the activity's layout) in which your fragment layout will be inserted

And

To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout.

You cannot define fragments as views or viewgroups.Fragments are more than that.The easiest way to visualize fragment is to think of them as chunks of an activity having own xml appearance,own behaviour with own life cycle callbacks.They always run on top of an activity allowing you to perform operations such as add,replace etc on them at run time.This way you can switch between your layouts effectively and efficiently.
To understand onCreateView method,consider the following explanation:

public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
         View view =inflater.inflate(R.layout.example_fragment, container, false);
      return view;

    }

this returns a single View object, always a ViewGroup , with the set of View object that defines the Fragment's UI. The Activity calls this event handler when it is time for the Fragment to provide its UI for display.

碎片是一种不需要全屏显示的活动,它可以将屏幕分成很多碎片,因此非常适合手机和平板电脑使用。

我认为没有,activity(fragment)控制视图显示的内容,viewGroup扩展视图并实现ViewManger。只有与活动负载相关的View才能通过电话显示布局。Activity是一个Group,view可以在此容器中正常工作

Neither. Fragment is a base class.

From https://developer.android.com/guide/components/fragments.html

A Fragment represents a behavior or a portion of user interface in an Activity

Fragment contains a field:

// The View generated for this fragment.
View mView;

that is generated in onCreateView which has the implementation:

@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        Bundle savedInstanceState) {
    return null;
}

So if you want a Fragment with a View then @Override that method. And then the Fragment can be shown to the user if you use the appropriate fragment transaction from an Activity or nested Fragment .

片段是与主机活动生命周期相关联的自定义视图的包装。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM