'Reusing a fragment with different task

I've got some fragments with a group of buttons inside them which are reused across my app, for example: fragment1withbuttons fragment2withbuttons

Depending on a state in which my app is in they need serve different functionalities, so I created an interface ICommand which i pass to every set of those buttons in constructor of the fragment like that:

public class Fragment2 extends Fragment {

    private ConstraintLayout first,second,third,fourth;
    private ICommand command;

    public Fragment2(ICommand command) {
        super(R.layout.fragment2);
        this.command = command;
    }

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

        View view = inflater.inflate(R.layout.fragment2, rootView, true);
        first = rootView.findViewById(R.id.first);
        first.setOnClickListener((v)-> command.execute1());
        second = rootView.findViewById(R.id.second);
        second.setOnClickListener((v)-> command.execute2());
        third = rootView.findViewById(R.id.third);
        third.setOnClickListener((v)-> command.execute3());
        fourth = rootView.findViewById(R.id.fourth);
        fourth.setOnClickListener((v)->command.execute4());
        return view;
    }
}

I am aware that this is a code smell and when system would like to recreate a fragment it would use a non-parametric constructor and there will be a problem.

I've tried a viewModel approach to the problem, but when one this fragment has 5 maybe 10 different use cases it becomes very messy. Should it be like that or am I missing something?

Thanks in advance for any advices



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source