1

I am developing a carpool application using our mCruiseOn platform. I have 2 activity's that I need to code, both the activity's have 90% the same code/flow and functionality. I can create a layout xml and just include it in both my layout's but how do I manage the code part of it. The intent is to not duplicate code, but yet keep it clean and manageable.

I need the common code to manage the findViewById, setOnClickListener and onClick method. As a example, both activities take start and end locations in gps. Both activity's have a time/date dialog button.

Some thoughts

  1. So GetGPSAndTimeActivity where I do all the findViewById, onClickListener, onCreateDialog. Then should I extend from GetGPSAndTimeActivity ?
  2. Use Fragments like Fragment in Android 2.3.3 and lesser

I prefer option 1.

Community
  • 1
  • 1
Siddharth
  • 9,349
  • 16
  • 86
  • 148

1 Answers1

1

That depends on your situation. Lets say you have an Activity A that does some stuff and an Activity B that does exactly the same stuff like A but a little bit more (like adding a few buttons).

In that case you can let Activity B extend your Activity A. B just adds what's missing.

If Activity A and B have a lot in common, but if there are also slight differences, to be precise: if Activity A contains code that is not needed by B you should create one abstract base class C for both activities A and B which contains only the common sub-set of code. Let A and B extend C and add to A and B their individual extra-code.

As for using Fragments or not: I'd go for it. In the long run you'll have less troubles with supporting tablets / multiple screen sizes and you can easily re-use them in different contexts.

Let's assume your boss / client suddenly wants that fancy ViewPager feature we know from Google Play (swiping screens left and right for switching categories). If you were using Fragments in the first place, this change can be done very easily and quickly. If you were using Activities instead, you need to re-arrange a great deal of code.

tiguchi
  • 5,392
  • 1
  • 33
  • 39