0

I recently inherited a project where I have a lot of fragments that share the same functions.

I want to refactor so that I have a BaseFragment where all these other fragments can extend from and where all shared functions exist. The only issue I've run into is that these fragments extend from different classes: TaskListFragment and TaskFragment.

Is there a way for me to implement BaseFragment so that the different types of fragments can use its methods - similar to how ruby modules work?

Huy
  • 10,806
  • 13
  • 55
  • 99

2 Answers2

0

Because Java doesn't support multiple inheritance, I think the best solution could be create a helper class which receive a Fragment as a constructor parameter and perform certain task calling its appropriates routines.

CommonTaskFragment

public class CommonTaskFragment {

    private Fragment _fragment;

    public CommonTaskFragment(Fragment fragment) {
        _fragment = fragment;
    }

    public void doTask1() {
        //Do something with the fragment instance
    }

    public void doTask2() {
        //Do something with the fragment instance
    }

}

TestFragment

public class TestFragment extends Fragment {

    private CommonTaskFragment _commonTask;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        _commonTask = new CommonTaskFragment(this);

        _commonTask.doTask1();
        _commonTask.doTask2();
    }

}
Víctor Albertos
  • 8,093
  • 5
  • 43
  • 71
0

You would have to implement an interface into TaskListFragment and TaskFragment. They would share the methods but they could/would have to be implemented separately inside the classes. Children of each class would just call the method. There is a much more complicated way of doing this but an interface is probably your best bet. This question should shed a little more light on the issue.

Java Multiple Inheritance

Community
  • 1
  • 1
gllowmas
  • 330
  • 1
  • 2
  • 11