Reading values from the Dimens file!

One of our Android apps demanded an infinite carousel with images overlapping each other. Surprisingly enough there are not too many examples out there on how to do this!

We used a ViewPager to create the carousel taking inspiration from https://github.com/mrleolink/SimpleInfiniteCarousel.

We had to make some changes here( another post on our carousel and maybe even the code itself soon!) but what we want to focus on in this post is how we make the carousel images overlap.

A typical way to do this is to give a negative margin to the ViewPager using ViewPager.setPageMargin(int). However giving a static number here will make change the margin across devices of different screensizes and resolutions. We need to add this margin to the dimens file and create a different dimens file for different resolutions. Here is what we did

  • Add a dimens file to the Values folder with

<dimen name=”carousel_margin”>-450dp</dimen>//this was our value for the normal size hd resolution

  • Set the Margin using the value from dimen file as

float density = getResources().getDisplayMetrics().density;

float dimenvalue= getResources().getDimension(R.dimen.carousel_margin);

float margin=dimenvalue/density;

viewPager.setPageMargin((int)margin);

Remember that dimens file returns value based on the density of the screen hence we need to divide the value by the density

  • Now based on whether your device is small, normal, large or xlarge and then low, medium, high, xhigh or xxhigh density you will need to change the margin value to get the correct overlap between the images.
  • Based on your target screensize you will need to define as many dimens files. We created the following dimens files for various resolutions and screen-sizes. Ensure you add a dimens file in the default Values folder for default fallbacks!

clip_image002[16]

Once we added all the dimens files , we used the studio simulators to finetune the margins on various sizes and resolutions and we were good to go!!

Team Cennest!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>