Android fragment inheritance

Is it possible / to recommend that different fragments inherit from each other in Android?

What would be the best way to initialize things that have already been initialized in the superclass and add something to it? (-> for example, like regular subclasses that use super () in their constructor and then initialize other objects)

I looked on the Internet, but I did not find much information about this. I know it is possible to make return super.onCreateView (), but after that you will not be able to initialize other objects / views ....

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView()??? //initialize other objects here //you have to return a view ... } 
+5
source share
1 answer

Yes, it is allowed. Why not? For example, if you have several fragments that display lists, you can put all common methods in a FragmentList and then inherit other fragments, adding only unique methods or redefining them from super, if necessary.

But overriding onCreateView() can cause difficulties in handling layouts. In my last project, I instead created the inflateFragment() method in a superclass as follows:

Basefragment.java

 protected View inflateFragment(int resId, LayoutInflater inflater, ViewGroup container) { View view = inflater.inflate(resId, container, false); FrameLayout layout = (FrameLayout)view.findViewById(R.id.fragment_layout); /* * Inflate shared layouts here */ . . . setHasOptionsMenu(true); return view; } 

Due to the structure, each fragment layout resource is wrapped in a FrameLayout using id = fragment_layout . But you can use LinearLayout or another parent view you need.

And then in the inherited fragments:

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflateFragment(R.layout.my_fragment, inflater, container); /* * Do things related to this fragment */ ... return view; } 
+11
source

Source: https://habr.com/ru/post/1203437/


All Articles