Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments inheritance Android

Is it possible/recommanded to let different fragments inherit from each other in Android?

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

I looked on the internet but i didn't found much information on this. I know that it's possible to do return super.onCreateView() but you can't initialize other objects/views after that....

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {

    super.onCreateView()???


    //initialize other objects here

    //you have to return a view ...
}
like image 471
DennisVA Avatar asked Sep 25 '14 22:09

DennisVA


1 Answers

Yes, it is allowed. Why not? For example, if you have a number of Fragments, that display lists, you could put all common methods in FragmentList, and then inherit other fragments, adding only unique methods or overriding the ones from super if needed.

But overriding onCreateView() could raise difficulties in layouts handling. In my recent project I instead created a method inflateFragment() in the super class 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;
}

Because of the structure, each and every fragment layout resource is wrapped in a FrameLayout with id = fragment_layout. But you're free to use LinearLayout or whatever parent view you need.

And then in 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;
}
like image 192
Alexander Zhak Avatar answered Oct 22 '22 01:10

Alexander Zhak