Reputation: 694
So, I have a ViewPager
and I want to realize a simple Page-Indicator
like Tinder does with its pics:
I thought it would be easy to find a library, but for the life of me, I can't find any.
I don't care if the bar is realized by manipulating the width of a dot or with a drawable, the only thing the library should do is stretching the bars, so that they always take 100% of the width of the ViewPager
.
Anyone know a library like that, or is it easy to realize this without help of a library?
Upvotes: 2
Views: 1936
Reputation: 1121
Let's solve this problem step by step.
First, Add Jake Wharton's ViewPager Library in your project. Go to your build.gradle (Module:app) and add this line and sync your project.
implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
Second, Add LinePageIndicator in your xml file where your viewPager is.
<com.viewpagerindicator.LinePageIndicator
android:id="@+id/indicator"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:strokeWidth="4dp"
app:unselectedColor="#FF888888"
app:selectedColor="#FF880000"/>
Third and final step, after attaching a adapter to your viewpager, add this code to get your desired output.
LinePageIndicator linePageIndicator = view.findViewById(R.id.indicator);
linePageIndicator.setViewPager(viewPager);
//As we are measuring screen width, you should put the calculation inside onGlobalLayoutListener to get the correct screen width
linePageIndicator.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int numberOfItems = viewPager.getChildCount();
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
float widthPixel = displayMetrics.widthPixels;
float itemWidth = widthPixel/numberOfItems;
linePageIndicator.setLineWidth(itemWidth);
}
});
And that's it, you've got a full screen wide lineindicator.
Upvotes: 11