Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Decorator pattern for Android views

NOTE: the actual question(s) is in the What my questions are section. The other sections are provided for giving better overview of the problem.

TASK

I want to decorate Android view using the Decorator design pattern. For my question I will be using decorating ViewPager as an example, but I believe the solution will be more general.

WHY DO I NEED IT

I want to be able to reuse different augmentations on the standard views in different solutions of mine. E.g. now I have timer-switching ViewPager and ViewPager that notifies me when the user reaches its end. With this solution I am aiming at adding auto-switching notifying ViewPager (i.e. combining both my current extensions) in my next solution a one-liner. Decorator pattern is exactly for that.

WHAT MY CURRENT APPROACH IS

  • I already wrapped the targeted ViewPager in ViewPagerDecorator
  • I also did the desired extensions of the decorator - AutoSwitchViewPager and NotifyOutOfBoundsViewPager (based on this). Now I can even do

    new AutoSwitchViewPager(new NotifyOutOfBoundsViewPager(viewPager)).

  • Now I am trying to figure out how to place this run-time created view in the layout. I am currently trying to figure out if I can replace ordinary ViewPager from layout propagating its xml attributes to the decorated view.

WHAT MY QUESTIONS ARE

  • Is there a way to copy over the xml attributes from a layout-defined view to runtime constructed one (LayoutParameters at least)
  • An alternative would be to use ViewStub, but I did not find a way to inflate ViewStub with something completely run-time constructed (without using xml Layout). Is there such a way?

WHAT HAVE I READ

I have stumbled upon these related resources:

  • Decorating Android views - this is not entirely decorating the views in the sense that the decorator would not subscribe to the different events of the view. The decoration needs to be triggered by a special trigger method. However, the decorations I aim for truly need to act as full extensions of the decorated class.
  • Decorator pattern Android - Here the decoration is again triggered via special method
  • Decorating an Android activity - with all the respect I have for ComonsWare I am very far away from questioning his statement. On the other hand, I believe that the views in Android allow you for more runtime modifications than the activities, so I still my case is plausible.
like image 950
Boris Strandjev Avatar asked Nov 06 '14 08:11

Boris Strandjev


1 Answers

After weeks of struggle and applying few different design approaches I think that I finally got the solution! As the solution is not as easy to explain as to fit in SO post I created a blog post to explain all my struggles. I also accompany my explanations with source code to demonstrate my ideas available here.

like image 177
Boris Strandjev Avatar answered Oct 29 '22 04:10

Boris Strandjev