Use more optimized way to detect direction in PagerIndicatorView

This commit is contained in:
Ebrahim Byagowi 2020-04-12 14:10:51 +04:30
parent 430e0d403e
commit 17962b57a0
1 changed files with 6 additions and 1 deletions

View File

@ -9,10 +9,13 @@ import android.util.AttributeSet;
import android.view.View; import android.view.View;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.text.TextUtilsCompat;
import androidx.core.view.ViewCompat; import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2; import androidx.viewpager2.widget.ViewPager2;
import java.util.Locale;
public class PagerIndicatorView extends View { public class PagerIndicatorView extends View {
private final Paint paint = new Paint(); private final Paint paint = new Paint();
private float position = 0; private float position = 0;
@ -56,11 +59,13 @@ public class PagerIndicatorView extends View {
invalidate(); invalidate();
} }
}); });
boolean isLocaleRtl = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault())
== ViewCompat.LAYOUT_DIRECTION_RTL;
pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override @Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
PagerIndicatorView.this.position = position + positionOffset; PagerIndicatorView.this.position = position + positionOffset;
if (ViewCompat.getLayoutDirection(pager) == ViewCompat.LAYOUT_DIRECTION_RTL) { if (isLocaleRtl) {
PagerIndicatorView.this.position = numPages - 1 - PagerIndicatorView.this.position; PagerIndicatorView.this.position = numPages - 1 - PagerIndicatorView.this.position;
} }
invalidate(); invalidate();