Pankaj Goyal
Pankaj Goyal

Reputation: 103

Extending Fragment in Android

I have a created a Base Fragment. This Fragment contains 2 buttons on the right hand side.Now I want to created two more fragments which should be similar to the above base fragment but should have different control on the left hand side. For example FragmentA should have additional textView on left hand side. FragmentB should have textView and ImageButton on the left hand side. What is the good way to implement this ? Should I add these control programmatically to the BaseFragment in onCreateView call of the extended FragmentA and FragmentB. Or do I need to create different layout file for extended fragments which includes the base Fragment.In this case how would I inflate the base and extended fragment?

Upvotes: 1

Views: 1312

Answers (1)

Michael
Michael

Reputation: 54725

There're multiple ways to do that. So here're three of them I came up with:

  1. Don't use inheritance. Instead add the reusable fragment as a nested fragment to FragmentA and FragmentB. With this approach it becomes a little difficult to send data to the nested fragment and listen to events from it.
  2. Add an abstract method that inflates and configures an additional layout. Then subclass the fragment and override this method. This approach is pretty good if the inner layout is always positioned in the same way but may have different contents.
  3. Add a layoutId parameter to the constructor of the base fragment class and pass if from subclasses. Override onViewCreated() in subclasses, call super implementation and perform subclass related configuration.

Upvotes: 1

Related Questions