1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.settings.widget; 18 19 import android.content.Context; 20 import android.support.v4.view.ViewPager; 21 import android.text.TextUtils; 22 import android.util.AttributeSet; 23 import android.view.View; 24 25 import java.util.Locale; 26 27 /** 28 * A {@link ViewPager} that's aware of RTL changes when used with FragmentPagerAdapter. 29 */ 30 public final class RtlCompatibleViewPager extends ViewPager { 31 32 /** 33 * Callback interface for responding to changing state of the selected page. 34 * Positions supplied will always be the logical position in the adapter - 35 * that is, the 0 index corresponds to the left-most page in LTR and the 36 * right-most page in RTL. 37 */ 38 RtlCompatibleViewPager(Context context)39 public RtlCompatibleViewPager(Context context) { 40 this(context, null /* attrs */); 41 } 42 RtlCompatibleViewPager(Context context, AttributeSet attrs)43 public RtlCompatibleViewPager(Context context, AttributeSet attrs) { 44 super(context, attrs); 45 } 46 47 @Override getCurrentItem()48 public int getCurrentItem() { 49 return getRtlAwareIndex(super.getCurrentItem()); 50 } 51 52 @Override setCurrentItem(int item)53 public void setCurrentItem(int item) { 54 super.setCurrentItem(getRtlAwareIndex(item)); 55 } 56 57 /** 58 * Get a "RTL friendly" index. If the locale is LTR, the index is returned as is. 59 * Otherwise it's transformed so view pager can render views using the new index for RTL. For 60 * example, the second view will be rendered to the left of first view. 61 * 62 * @param index The logical index. 63 */ getRtlAwareIndex(int index)64 public int getRtlAwareIndex(int index) { 65 // Using TextUtils rather than View.getLayoutDirection() because LayoutDirection is not 66 // defined until onMeasure, and this is called before then. 67 if (TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) 68 == View.LAYOUT_DIRECTION_RTL) { 69 return getAdapter().getCount() - index - 1; 70 } 71 return index; 72 } 73 } 74