├── .gitignore ├── LICENSE ├── README.md ├── TextViewPager ├── AndroidManifest.xml ├── libs │ └── android-support-v4.jar ├── proguard-project.txt ├── project.properties ├── res │ └── values │ │ ├── attrs.xml │ │ ├── defaults.xml │ │ └── strings.xml └── src │ ├── android │ └── support │ │ └── v4 │ │ └── view │ │ └── DirectionalViewPager.java │ └── co │ └── paulburke │ └── android │ └── textviewpager │ ├── ColumnedTextView.java │ ├── PagingLayoutListener.java │ ├── TextViewPager.java │ ├── TextViewPagerAdapter.java │ ├── TextViewPagerIndicator.java │ └── TextViewUtils.java └── TextViewPagerExample ├── AndroidManifest.xml ├── proguard-project.txt ├── project.properties ├── res ├── drawable-hdpi │ └── ic_launcher.png ├── drawable-mdpi │ └── ic_launcher.png ├── drawable-xhdpi │ └── ic_launcher.png ├── layout │ ├── activity_styled_vertical.xml │ └── text.xml ├── values-sw300dp-land │ └── integers.xml ├── values-sw600dp │ ├── dimens.xml │ └── integers.xml ├── values-sw720dp-land │ ├── dimens.xml │ └── integers.xml ├── values-v11 │ └── styles.xml └── values │ ├── dimens.xml │ ├── integers.xml │ ├── strings.xml │ └── styles.xml └── src └── co └── paulburke └── android └── textviewpagerexample ├── BasicHorizontalActivity.java ├── ColumnsActivity.java ├── MainActivity.java └── StyledVerticalActivity.java /.gitignore: -------------------------------------------------------------------------------- 1 | # ndk generated files 2 | **/obj/ 3 | 4 | # built application files 5 | *.apk 6 | *.ap_ 7 | 8 | # lint files 9 | lint.xml 10 | 11 | # files for the dex VM 12 | *.dex 13 | 14 | # Java class files 15 | *.class 16 | 17 | # generated files 18 | bin/ 19 | gen/ 20 | classes/ 21 | gen-external-apklibs/ 22 | 23 | # maven output folder 24 | target 25 | 26 | # Local configuration file (sdk path, etc) 27 | local.properties 28 | 29 | # Eclipse project files 30 | .classpath 31 | .project 32 | .metadata 33 | .settings 34 | 35 | # Proguard folder generated by Eclipse 36 | proguard/ 37 | 38 | # IntelliJ files 39 | *.iml 40 | *.ipr 41 | *.iws 42 | .idea/ 43 | 44 | # OSX files 45 | .DS_Store 46 | 47 | # Windows files 48 | Thumbs.db 49 | 50 | # vi swap files 51 | *.swp 52 | 53 | # backup files 54 | *.bak -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2013 Paul Burke 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Android-TextViewPager 2 | ===================== 3 | 4 | A ViewPager that automatically pages text based on the available space. More information coming. 5 | -------------------------------------------------------------------------------- /TextViewPager/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 20 | 21 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /TextViewPager/libs/android-support-v4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iPaulPro/Android-TextViewPager/3b8af8090b441610f327a367ec0d7a1f32f68e54/TextViewPager/libs/android-support-v4.jar -------------------------------------------------------------------------------- /TextViewPager/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /TextViewPager/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-19 15 | android.library=true 16 | -------------------------------------------------------------------------------- /TextViewPager/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /TextViewPager/res/values/defaults.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | true 19 | 600 20 | 400 21 | #FF33B5E5 22 | -------------------------------------------------------------------------------- /TextViewPager/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | Unable to load text 20 | 21 | -------------------------------------------------------------------------------- /TextViewPager/src/android/support/v4/view/DirectionalViewPager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * Copyright (C) 2011 Jake Wharton 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package android.support.v4.view; 19 | 20 | import android.content.Context; 21 | import android.database.DataSetObserver; 22 | import android.os.Build; 23 | import android.os.Parcelable; 24 | import android.util.AttributeSet; 25 | import android.util.Log; 26 | import android.view.MotionEvent; 27 | import android.view.VelocityTracker; 28 | import android.view.View; 29 | import android.view.ViewConfiguration; 30 | import android.view.ViewGroup; 31 | import android.widget.Scroller; 32 | 33 | import java.util.ArrayList; 34 | 35 | /** 36 | * Layout manager that allows the user to flip horizontally or vertically 37 | * through pages of data. You supply an implementation of a {@link PagerAdapter} 38 | * to generate the pages that the view shows. 39 | */ 40 | public class DirectionalViewPager extends ViewPager { 41 | private static final String TAG = "DirectionalViewPager"; 42 | private static final String XML_NS = "http://schemas.android.com/apk/res/android"; 43 | private static final boolean DEBUG = false; 44 | 45 | private static final boolean USE_CACHE = false; 46 | 47 | public static final int HORIZONTAL = 0; 48 | public static final int VERTICAL = 1; 49 | 50 | private final ArrayList mItems = new ArrayList(); 51 | 52 | private PagerAdapter mAdapter; 53 | private int mCurItem; // Index of currently displayed page. 54 | private int mRestoredCurItem = -1; 55 | private Parcelable mRestoredAdapterState = null; 56 | private ClassLoader mRestoredClassLoader = null; 57 | private Scroller mScroller; 58 | 59 | private int mChildWidthMeasureSpec; 60 | private int mChildHeightMeasureSpec; 61 | private boolean mInLayout; 62 | 63 | private boolean mScrollingCacheEnabled; 64 | 65 | private boolean mPopulatePending; 66 | private boolean mScrolling; 67 | 68 | private boolean mIsBeingDragged; 69 | private boolean mIsUnableToDrag; 70 | private int mTouchSlop; 71 | private float mInitialMotion; 72 | /** 73 | * Position of the last motion event. 74 | */ 75 | private float mLastMotionX; 76 | private float mLastMotionY; 77 | private int mOrientation = HORIZONTAL; 78 | /** 79 | * ID of the active pointer. This is used to retain consistency during 80 | * drags/flings if multiple pointers are used. 81 | */ 82 | private int mActivePointerId = INVALID_POINTER; 83 | /** 84 | * Sentinel value for no current active pointer. Used by 85 | * {@link #mActivePointerId}. 86 | */ 87 | private static final int INVALID_POINTER = -1; 88 | 89 | /** 90 | * Determines speed during touch scrolling 91 | */ 92 | private VelocityTracker mVelocityTracker; 93 | private int mMinimumVelocity; 94 | private int mMaximumVelocity; 95 | 96 | private DataSetObserver mObserver; 97 | 98 | private OnPageChangeListener mOnPageChangeListener; 99 | 100 | private int mScrollState = SCROLL_STATE_IDLE; 101 | 102 | public DirectionalViewPager(Context context) { 103 | super(context); 104 | initViewPager(); 105 | } 106 | 107 | public DirectionalViewPager(Context context, AttributeSet attrs) { 108 | super(context, attrs); 109 | initViewPager(); 110 | 111 | // We default to horizontal, only change if a value is explicitly 112 | // specified 113 | if (attrs != null) { 114 | int orientation = attrs.getAttributeIntValue(XML_NS, "orientation", -1); 115 | if (orientation != -1) { 116 | setOrientation(orientation); 117 | } 118 | } 119 | } 120 | 121 | @Override 122 | void initViewPager() { 123 | super.initViewPager(); 124 | setWillNotDraw(false); 125 | mScroller = new Scroller(getContext()); 126 | final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 127 | mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); 128 | mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 129 | mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 130 | } 131 | 132 | private void setScrollState(int newState) { 133 | if (mScrollState == newState) { 134 | return; 135 | } 136 | 137 | mScrollState = newState; 138 | if (mOnPageChangeListener != null) { 139 | mOnPageChangeListener.onPageScrollStateChanged(newState); 140 | } 141 | } 142 | 143 | @Override 144 | public void setAdapter(PagerAdapter adapter) { 145 | super.setAdapter(adapter); 146 | 147 | if (mAdapter != null) { 148 | mAdapter.registerDataSetObserver(null); 149 | } 150 | 151 | mAdapter = adapter; 152 | 153 | if (mAdapter != null) { 154 | if (mObserver == null) { 155 | mObserver = new PagerObserver(); 156 | } 157 | mAdapter.registerDataSetObserver(mObserver); 158 | mPopulatePending = false; 159 | if (mRestoredCurItem >= 0) { 160 | mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); 161 | setCurrentItemInternal(mRestoredCurItem, false, true); 162 | mRestoredCurItem = -1; 163 | mRestoredAdapterState = null; 164 | mRestoredClassLoader = null; 165 | } else { 166 | populate(); 167 | } 168 | } 169 | } 170 | 171 | @Override 172 | public PagerAdapter getAdapter() { 173 | return mAdapter; 174 | } 175 | 176 | @Override 177 | public int getCurrentItem() { 178 | return mCurItem; 179 | } 180 | 181 | @Override 182 | public void setCurrentItem(int item) { 183 | mPopulatePending = false; 184 | setCurrentItemInternal(item, true, false); 185 | } 186 | 187 | @Override 188 | void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { 189 | if (mAdapter == null || mAdapter.getCount() <= 0) { 190 | setScrollingCacheEnabled(false); 191 | return; 192 | } 193 | if (!always && mCurItem == item && mItems.size() != 0) { 194 | setScrollingCacheEnabled(false); 195 | return; 196 | } 197 | if (item < 0) { 198 | item = 0; 199 | } else if (item >= mAdapter.getCount()) { 200 | item = mAdapter.getCount() - 1; 201 | } 202 | if (item > (mCurItem + 1) || item < (mCurItem - 1)) { 203 | // We are doing a jump by more than one page. To avoid 204 | // glitches, we want to keep all current pages in the view 205 | // until the scroll ends. 206 | for (int i = 0; i < mItems.size(); i++) { 207 | mItems.get(i).scrolling = true; 208 | } 209 | } 210 | final boolean dispatchSelected = mCurItem != item; 211 | mCurItem = item; 212 | populate(); 213 | if (smoothScroll) { 214 | if (mOrientation == HORIZONTAL) { 215 | smoothScrollTo(getWidth() * item, 0); 216 | } else { 217 | smoothScrollTo(0, getHeight() * item); 218 | } 219 | if (dispatchSelected && mOnPageChangeListener != null) { 220 | mOnPageChangeListener.onPageSelected(item); 221 | } 222 | } else { 223 | if (dispatchSelected && mOnPageChangeListener != null) { 224 | mOnPageChangeListener.onPageSelected(item); 225 | } 226 | completeScroll(); 227 | if (mOrientation == HORIZONTAL) { 228 | scrollTo(getWidth() * item, 0); 229 | } else { 230 | scrollTo(0, getHeight() * item); 231 | } 232 | } 233 | } 234 | 235 | @Override 236 | public void setOnPageChangeListener(OnPageChangeListener listener) { 237 | mOnPageChangeListener = listener; 238 | } 239 | 240 | public OnPageChangeListener getOnPageChangeListener() { 241 | return mOnPageChangeListener; 242 | } 243 | 244 | /** 245 | * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 246 | * 247 | * @param dx the number of pixels to scroll by on the X axis 248 | * @param dy the number of pixels to scroll by on the Y axis 249 | */ 250 | @Override 251 | void smoothScrollTo(int x, int y) { 252 | if (getChildCount() == 0) { 253 | // Nothing to do. 254 | setScrollingCacheEnabled(false); 255 | return; 256 | } 257 | int sx = getScrollX(); 258 | int sy = getScrollY(); 259 | int dx = x - sx; 260 | int dy = y - sy; 261 | if (dx == 0 && dy == 0) { 262 | completeScroll(); 263 | return; 264 | } 265 | 266 | setScrollingCacheEnabled(true); 267 | mScrolling = true; 268 | setScrollState(SCROLL_STATE_SETTLING); 269 | mScroller.startScroll(sx, sy, dx, dy); 270 | invalidate(); 271 | } 272 | 273 | @Override 274 | android.support.v4.view.ViewPager.ItemInfo addNewItem(int position, int index) { 275 | ItemInfo ii = new ItemInfo(); 276 | ii.position = position; 277 | ii.object = mAdapter.instantiateItem(this, position); 278 | if (index < 0) { 279 | mItems.add(ii); 280 | } else { 281 | mItems.add(index, ii); 282 | } 283 | return ii; 284 | } 285 | 286 | @Override 287 | void dataSetChanged() { 288 | // This method only gets called if our observer is attached, so mAdapter 289 | // is non-null. 290 | 291 | boolean needPopulate = mItems.isEmpty() && mAdapter.getCount() > 0; 292 | int newCurrItem = -1; 293 | 294 | for (int i = 0; i < mItems.size(); i++) { 295 | final ItemInfo ii = mItems.get(i); 296 | final int newPos = mAdapter.getItemPosition(ii.object); 297 | 298 | if (newPos == PagerAdapter.POSITION_UNCHANGED) { 299 | continue; 300 | } 301 | 302 | if (newPos == PagerAdapter.POSITION_NONE) { 303 | mItems.remove(i); 304 | i--; 305 | mAdapter.destroyItem(this, ii.position, ii.object); 306 | needPopulate = true; 307 | 308 | if (mCurItem == ii.position) { 309 | // Keep the current item in the valid range 310 | newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1)); 311 | } 312 | continue; 313 | } 314 | 315 | if (ii.position != newPos) { 316 | if (ii.position == mCurItem) { 317 | // Our current item changed position. Follow it. 318 | newCurrItem = newPos; 319 | } 320 | 321 | ii.position = newPos; 322 | needPopulate = true; 323 | } 324 | } 325 | 326 | if (newCurrItem >= 0) { 327 | // TODO This currently causes a jump. 328 | setCurrentItemInternal(newCurrItem, false, true); 329 | needPopulate = true; 330 | } 331 | if (needPopulate) { 332 | populate(); 333 | requestLayout(); 334 | } 335 | } 336 | 337 | @Override 338 | void populate() { 339 | if (mAdapter == null) { 340 | return; 341 | } 342 | 343 | // Bail now if we are waiting to populate. This is to hold off 344 | // on creating views from the time the user releases their finger to 345 | // fling to a new position until we have finished the scroll to 346 | // that position, avoiding glitches from happening at that point. 347 | if (mPopulatePending) { 348 | if (DEBUG) 349 | Log.i(TAG, "populate is pending, skipping for now..."); 350 | return; 351 | } 352 | 353 | // Also, don't populate until we are attached to a window. This is to 354 | // avoid trying to populate before we have restored our view hierarchy 355 | // state and conflicting with what is restored. 356 | if (getWindowToken() == null) { 357 | return; 358 | } 359 | 360 | mAdapter.startUpdate(this); 361 | 362 | final int startPos = mCurItem > 0 ? mCurItem - 1 : mCurItem; 363 | final int count = mAdapter.getCount(); 364 | final int endPos = mCurItem < (count - 1) ? mCurItem + 1 : count - 1; 365 | 366 | if (DEBUG) 367 | Log.v(TAG, "populating: startPos=" + startPos + " endPos=" + endPos); 368 | 369 | // Add and remove pages in the existing list. 370 | int lastPos = -1; 371 | for (int i = 0; i < mItems.size(); i++) { 372 | ItemInfo ii = mItems.get(i); 373 | if ((ii.position < startPos || ii.position > endPos) && !ii.scrolling) { 374 | if (DEBUG) 375 | Log.i(TAG, "removing: " + ii.position + " @ " + i); 376 | mItems.remove(i); 377 | i--; 378 | mAdapter.destroyItem(this, ii.position, ii.object); 379 | } else if (lastPos < endPos && ii.position > startPos) { 380 | // The next item is outside of our range, but we have a gap 381 | // between it and the last item where we want to have a page 382 | // shown. Fill in the gap. 383 | lastPos++; 384 | if (lastPos < startPos) { 385 | lastPos = startPos; 386 | } 387 | while (lastPos <= endPos && lastPos < ii.position) { 388 | if (DEBUG) 389 | Log.i(TAG, "inserting: " + lastPos + " @ " + i); 390 | addNewItem(lastPos, i); 391 | lastPos++; 392 | i++; 393 | } 394 | } 395 | lastPos = ii.position; 396 | } 397 | 398 | // Add any new pages we need at the end. 399 | lastPos = mItems.size() > 0 ? mItems.get(mItems.size() - 1).position : -1; 400 | if (lastPos < endPos) { 401 | lastPos++; 402 | lastPos = lastPos > startPos ? lastPos : startPos; 403 | while (lastPos <= endPos) { 404 | if (DEBUG) 405 | Log.i(TAG, "appending: " + lastPos); 406 | addNewItem(lastPos, -1); 407 | lastPos++; 408 | } 409 | } 410 | 411 | if (DEBUG) { 412 | Log.i(TAG, "Current page list:"); 413 | for (int i = 0; i < mItems.size(); i++) { 414 | Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); 415 | } 416 | } 417 | 418 | mAdapter.finishUpdate(this); 419 | } 420 | 421 | public int getOrientation() { 422 | return mOrientation; 423 | } 424 | 425 | public void setOrientation(int orientation) { 426 | switch (orientation) { 427 | case HORIZONTAL: 428 | case VERTICAL: 429 | break; 430 | 431 | default: 432 | throw new IllegalArgumentException( 433 | "Only HORIZONTAL and VERTICAL are valid orientations."); 434 | } 435 | 436 | if (orientation == mOrientation) { 437 | return; 438 | } 439 | 440 | // Complete any scroll we are currently in the middle of 441 | completeScroll(); 442 | 443 | // Reset values 444 | mInitialMotion = 0; 445 | mLastMotionX = 0; 446 | mLastMotionY = 0; 447 | if (mVelocityTracker != null) { 448 | mVelocityTracker.clear(); 449 | } 450 | 451 | // Adjust scroll for new orientation 452 | mOrientation = orientation; 453 | if (mOrientation == HORIZONTAL) { 454 | scrollTo(mCurItem * getWidth(), 0); 455 | } else { 456 | scrollTo(0, mCurItem * getHeight()); 457 | } 458 | requestLayout(); 459 | } 460 | 461 | @Override 462 | public void addView(View child, int index, ViewGroup.LayoutParams params) { 463 | if (mInLayout) { 464 | addViewInLayout(child, index, params); 465 | child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); 466 | } else { 467 | super.addView(child, index, params); 468 | } 469 | 470 | if (USE_CACHE) { 471 | if (child.getVisibility() != GONE) { 472 | child.setDrawingCacheEnabled(mScrollingCacheEnabled); 473 | } else { 474 | child.setDrawingCacheEnabled(false); 475 | } 476 | } 477 | } 478 | 479 | @Override 480 | android.support.v4.view.ViewPager.ItemInfo infoForChild(View child) { 481 | for (int i = 0; i < mItems.size(); i++) { 482 | ItemInfo ii = mItems.get(i); 483 | if (mAdapter.isViewFromObject(child, ii.object)) { 484 | return ii; 485 | } 486 | } 487 | return null; 488 | } 489 | 490 | @Override 491 | protected void onAttachedToWindow() { 492 | super.onAttachedToWindow(); 493 | if (mAdapter != null) { 494 | populate(); 495 | } 496 | } 497 | 498 | @Override 499 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 500 | // For simple implementation, or internal size is always 0. 501 | // We depend on the container to specify the layout size of 502 | // our view. We can't really know what it is since we will be 503 | // adding and removing different arbitrary views and do not 504 | // want the layout to change as this happens. 505 | setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), 506 | getDefaultSize(0, heightMeasureSpec)); 507 | 508 | // Children are just made to fill our space. 509 | mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - 510 | getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY); 511 | mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - 512 | getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY); 513 | 514 | // Make sure we have created all fragments that we need to have shown. 515 | mInLayout = true; 516 | populate(); 517 | mInLayout = false; 518 | 519 | // Make sure all children have been properly measured. 520 | final int size = getChildCount(); 521 | for (int i = 0; i < size; ++i) { 522 | final View child = getChildAt(i); 523 | if (child.getVisibility() != GONE) { 524 | if (DEBUG) 525 | Log.v(TAG, "Measuring #" + i + " " + child 526 | + ": " + mChildWidthMeasureSpec + " x " + mChildHeightMeasureSpec); 527 | child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); 528 | } 529 | } 530 | } 531 | 532 | @Override 533 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 534 | super.onSizeChanged(w, h, oldw, oldh); 535 | 536 | // Make sure scroll position is set correctly. 537 | if (mOrientation == HORIZONTAL) { 538 | int scrollPos = mCurItem * w; 539 | if (scrollPos != getScrollX()) { 540 | completeScroll(); 541 | scrollTo(scrollPos, getScrollY()); 542 | } 543 | } else { 544 | int scrollPos = mCurItem * h; 545 | if (scrollPos != getScrollY()) { 546 | completeScroll(); 547 | scrollTo(getScrollX(), scrollPos); 548 | } 549 | } 550 | } 551 | 552 | @Override 553 | protected void onLayout(boolean changed, int l, int t, int r, int b) { 554 | mInLayout = true; 555 | populate(); 556 | mInLayout = false; 557 | 558 | final int count = getChildCount(); 559 | final int size = (mOrientation == HORIZONTAL) ? r - l : b - t; 560 | 561 | for (int i = 0; i < count; i++) { 562 | View child = getChildAt(i); 563 | ItemInfo ii; 564 | if (child.getVisibility() != GONE && (ii = infoForChild(child)) != null) { 565 | int off = size * ii.position; 566 | int childLeft = getPaddingLeft(); 567 | int childTop = getPaddingTop(); 568 | if (mOrientation == HORIZONTAL) { 569 | childLeft += off; 570 | } else { 571 | childTop += off; 572 | } 573 | if (DEBUG) 574 | Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object 575 | + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() 576 | + "x" + child.getMeasuredHeight()); 577 | child.layout(childLeft, childTop, 578 | childLeft + child.getMeasuredWidth(), 579 | childTop + child.getMeasuredHeight()); 580 | } 581 | } 582 | } 583 | 584 | @Override 585 | public void computeScroll() { 586 | if (DEBUG) 587 | Log.i(TAG, "computeScroll: finished=" + mScroller.isFinished()); 588 | if (!mScroller.isFinished()) { 589 | if (mScroller.computeScrollOffset()) { 590 | if (DEBUG) 591 | Log.i(TAG, "computeScroll: still scrolling"); 592 | int oldX = getScrollX(); 593 | int oldY = getScrollY(); 594 | int x = mScroller.getCurrX(); 595 | int y = mScroller.getCurrY(); 596 | 597 | if (oldX != x || oldY != y) { 598 | scrollTo(x, y); 599 | } 600 | 601 | if (mOnPageChangeListener != null) { 602 | int size; 603 | int value; 604 | if (mOrientation == HORIZONTAL) { 605 | size = getWidth(); 606 | value = x; 607 | } else { 608 | size = getHeight(); 609 | value = y; 610 | } 611 | 612 | final int position = value / size; 613 | final int offsetPixels = value % size; 614 | final float offset = (float) offsetPixels / size; 615 | mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); 616 | } 617 | 618 | // Keep on drawing until the animation has finished. 619 | invalidate(); 620 | return; 621 | } 622 | } 623 | 624 | // Done with scroll, clean up state. 625 | completeScroll(); 626 | } 627 | 628 | private void completeScroll() { 629 | boolean needPopulate; 630 | if ((needPopulate = mScrolling)) { 631 | // Done with scroll, no longer want to cache view drawing. 632 | setScrollingCacheEnabled(false); 633 | mScroller.abortAnimation(); 634 | int oldX = getScrollX(); 635 | int oldY = getScrollY(); 636 | int x = mScroller.getCurrX(); 637 | int y = mScroller.getCurrY(); 638 | if (oldX != x || oldY != y) { 639 | scrollTo(x, y); 640 | } 641 | setScrollState(SCROLL_STATE_IDLE); 642 | } 643 | mPopulatePending = false; 644 | mScrolling = false; 645 | for (int i = 0; i < mItems.size(); i++) { 646 | ItemInfo ii = mItems.get(i); 647 | if (ii.scrolling) { 648 | needPopulate = true; 649 | ii.scrolling = false; 650 | } 651 | } 652 | if (needPopulate) { 653 | populate(); 654 | } 655 | } 656 | 657 | @Override 658 | public boolean onInterceptTouchEvent(MotionEvent ev) { 659 | /* 660 | * This method JUST determines whether we want to intercept the motion. 661 | * If we return true, onMotionEvent will be called and we do the actual 662 | * scrolling there. 663 | */ 664 | 665 | final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; 666 | 667 | // Always take care of the touch gesture being complete. 668 | if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 669 | // Release the drag. 670 | if (DEBUG) 671 | Log.v(TAG, "Intercept done!"); 672 | mIsBeingDragged = false; 673 | mIsUnableToDrag = false; 674 | mActivePointerId = INVALID_POINTER; 675 | return false; 676 | } 677 | 678 | // Nothing more to do here if we have decided whether or not we 679 | // are dragging. 680 | if (action != MotionEvent.ACTION_DOWN) { 681 | if (mIsBeingDragged) { 682 | if (DEBUG) 683 | Log.v(TAG, "Intercept returning true!"); 684 | return true; 685 | } 686 | if (mIsUnableToDrag) { 687 | if (DEBUG) 688 | Log.v(TAG, "Intercept returning false!"); 689 | return false; 690 | } 691 | } 692 | 693 | switch (action) { 694 | case MotionEvent.ACTION_MOVE: { 695 | /* 696 | * mIsBeingDragged == false, otherwise the shortcut would have 697 | * caught it. Check whether the user has moved far enough from 698 | * his original down touch. 699 | */ 700 | 701 | /* 702 | * Locally do absolute value. mLastMotionY is set to the y value 703 | * of the down event. 704 | */ 705 | final int activePointerId = mActivePointerId; 706 | if (activePointerId == INVALID_POINTER 707 | && Build.VERSION.SDK_INT > Build.VERSION_CODES.DONUT) { 708 | // If we don't have a valid id, the touch down wasn't on 709 | // content. 710 | break; 711 | } 712 | 713 | final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); 714 | final float x = MotionEventCompat.getX(ev, pointerIndex); 715 | final float y = MotionEventCompat.getY(ev, pointerIndex); 716 | final float xDiff = Math.abs(x - mLastMotionX); 717 | final float yDiff = Math.abs(y - mLastMotionY); 718 | float primaryDiff; 719 | float secondaryDiff; 720 | 721 | if (mOrientation == HORIZONTAL) { 722 | primaryDiff = xDiff; 723 | secondaryDiff = yDiff; 724 | } else { 725 | primaryDiff = yDiff; 726 | secondaryDiff = xDiff; 727 | } 728 | 729 | if (DEBUG) 730 | Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); 731 | 732 | if (primaryDiff > mTouchSlop && primaryDiff > secondaryDiff) { 733 | if (DEBUG) 734 | Log.v(TAG, "Starting drag!"); 735 | mIsBeingDragged = true; 736 | setScrollState(SCROLL_STATE_DRAGGING); 737 | if (mOrientation == HORIZONTAL) { 738 | mLastMotionX = x; 739 | } else { 740 | mLastMotionY = y; 741 | } 742 | setScrollingCacheEnabled(true); 743 | } else { 744 | if (secondaryDiff > mTouchSlop) { 745 | // The finger has moved enough in the vertical 746 | // direction to be counted as a drag... abort 747 | // any attempt to drag horizontally, to work correctly 748 | // with children that have scrolling containers. 749 | if (DEBUG) 750 | Log.v(TAG, "Starting unable to drag!"); 751 | mIsUnableToDrag = true; 752 | } 753 | } 754 | break; 755 | } 756 | 757 | case MotionEvent.ACTION_DOWN: { 758 | /* 759 | * Remember location of down touch. ACTION_DOWN always refers to 760 | * pointer index 0. 761 | */ 762 | if (mOrientation == HORIZONTAL) { 763 | mLastMotionX = mInitialMotion = ev.getX(); 764 | mLastMotionY = ev.getY(); 765 | } else { 766 | mLastMotionX = ev.getX(); 767 | mLastMotionY = mInitialMotion = ev.getY(); 768 | } 769 | mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 770 | 771 | if (mScrollState == SCROLL_STATE_SETTLING) { 772 | // Let the user 'catch' the pager as it animates. 773 | mIsBeingDragged = true; 774 | mIsUnableToDrag = false; 775 | setScrollState(SCROLL_STATE_DRAGGING); 776 | } else { 777 | completeScroll(); 778 | mIsBeingDragged = false; 779 | mIsUnableToDrag = false; 780 | } 781 | 782 | if (DEBUG) 783 | Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY 784 | + " mIsBeingDragged=" + mIsBeingDragged 785 | + "mIsUnableToDrag=" + mIsUnableToDrag); 786 | break; 787 | } 788 | 789 | case MotionEventCompat.ACTION_POINTER_UP: 790 | onSecondaryPointerUp(ev); 791 | break; 792 | } 793 | 794 | /* 795 | * The only time we want to intercept motion events is if we are in the 796 | * drag mode. 797 | */ 798 | return mIsBeingDragged; 799 | } 800 | 801 | @Override 802 | public boolean onTouchEvent(MotionEvent ev) { 803 | 804 | if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { 805 | // Don't handle edge touches immediately -- they may actually belong 806 | // to one of our 807 | // descendants. 808 | return false; 809 | } 810 | 811 | if (mAdapter == null || mAdapter.getCount() == 0) { 812 | // Nothing to present or scroll; nothing to touch. 813 | return false; 814 | } 815 | 816 | if (mVelocityTracker == null) { 817 | mVelocityTracker = VelocityTracker.obtain(); 818 | } 819 | mVelocityTracker.addMovement(ev); 820 | 821 | final int action = ev.getAction(); 822 | 823 | switch (action & MotionEventCompat.ACTION_MASK) { 824 | case MotionEvent.ACTION_DOWN: { 825 | /* 826 | * If being flinged and user touches, stop the fling. isFinished 827 | * will be false if being flinged. 828 | */ 829 | completeScroll(); 830 | 831 | // Remember where the motion event started 832 | if (mOrientation == HORIZONTAL) { 833 | mLastMotionX = mInitialMotion = ev.getX(); 834 | } else { 835 | mLastMotionY = mInitialMotion = ev.getY(); 836 | } 837 | mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 838 | break; 839 | } 840 | case MotionEvent.ACTION_MOVE: 841 | if (!mIsBeingDragged) { 842 | final int pointerIndex = MotionEventCompat.findPointerIndex(ev, 843 | mActivePointerId); 844 | final float x = MotionEventCompat.getX(ev, pointerIndex); 845 | final float y = MotionEventCompat.getY(ev, pointerIndex); 846 | final float xDiff = Math.abs(x - mLastMotionX); 847 | final float yDiff = Math.abs(y - mLastMotionY); 848 | float primaryDiff; 849 | float secondaryDiff; 850 | 851 | if (mOrientation == HORIZONTAL) { 852 | primaryDiff = xDiff; 853 | secondaryDiff = yDiff; 854 | } else { 855 | primaryDiff = yDiff; 856 | secondaryDiff = xDiff; 857 | } 858 | 859 | if (DEBUG) 860 | Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); 861 | if (primaryDiff > mTouchSlop && primaryDiff > secondaryDiff) { 862 | if (DEBUG) 863 | Log.v(TAG, "Starting drag!"); 864 | mIsBeingDragged = true; 865 | if (mOrientation == HORIZONTAL) { 866 | mLastMotionX = x; 867 | } else { 868 | mLastMotionY = y; 869 | } 870 | setScrollState(SCROLL_STATE_DRAGGING); 871 | setScrollingCacheEnabled(true); 872 | } 873 | } 874 | if (mIsBeingDragged) { 875 | // Scroll to follow the motion event 876 | final int activePointerIndex = MotionEventCompat.findPointerIndex( 877 | ev, mActivePointerId); 878 | final float x = MotionEventCompat.getX(ev, activePointerIndex); 879 | final float y = MotionEventCompat.getY(ev, activePointerIndex); 880 | 881 | int size; 882 | float scroll; 883 | 884 | if (mOrientation == HORIZONTAL) { 885 | size = getWidth(); 886 | scroll = getScrollX() + (mLastMotionX - x); 887 | mLastMotionX = x; 888 | } else { 889 | size = getHeight(); 890 | scroll = getScrollY() + (mLastMotionY - y); 891 | mLastMotionY = y; 892 | } 893 | 894 | final float lowerBound = Math.max(0, (mCurItem - 1) * size); 895 | final float upperBound = 896 | Math.min(mCurItem + 1, mAdapter.getCount() - 1) * size; 897 | if (scroll < lowerBound) { 898 | scroll = lowerBound; 899 | } else if (scroll > upperBound) { 900 | scroll = upperBound; 901 | } 902 | if (mOrientation == HORIZONTAL) { 903 | // Don't lose the rounded component 904 | mLastMotionX += scroll - (int) scroll; 905 | scrollTo((int) scroll, getScrollY()); 906 | } else { 907 | // Don't lose the rounded component 908 | mLastMotionY += scroll - (int) scroll; 909 | scrollTo(getScrollX(), (int) scroll); 910 | } 911 | if (mOnPageChangeListener != null) { 912 | final int position = (int) scroll / size; 913 | final int positionOffsetPixels = (int) scroll % size; 914 | final float positionOffset = (float) positionOffsetPixels / size; 915 | mOnPageChangeListener.onPageScrolled(position, positionOffset, 916 | positionOffsetPixels); 917 | } 918 | } 919 | break; 920 | case MotionEvent.ACTION_UP: 921 | if (mIsBeingDragged) { 922 | final VelocityTracker velocityTracker = mVelocityTracker; 923 | velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 924 | int initialVelocity; 925 | float lastMotion; 926 | int sizeOverThree; 927 | 928 | if (mOrientation == HORIZONTAL) { 929 | initialVelocity = (int) VelocityTrackerCompat.getXVelocity( 930 | velocityTracker, mActivePointerId); 931 | lastMotion = mLastMotionX; 932 | sizeOverThree = getWidth() / 3; 933 | } else { 934 | initialVelocity = (int) VelocityTrackerCompat.getYVelocity( 935 | velocityTracker, mActivePointerId); 936 | lastMotion = mLastMotionY; 937 | sizeOverThree = getHeight() / 3; 938 | } 939 | 940 | mPopulatePending = true; 941 | if ((Math.abs(initialVelocity) > mMinimumVelocity) 942 | || Math.abs(mInitialMotion - lastMotion) >= sizeOverThree) { 943 | if (lastMotion > mInitialMotion) { 944 | setCurrentItemInternal(mCurItem - 1, true, true); 945 | } else { 946 | setCurrentItemInternal(mCurItem + 1, true, true); 947 | } 948 | } else { 949 | setCurrentItemInternal(mCurItem, true, true); 950 | } 951 | 952 | mActivePointerId = INVALID_POINTER; 953 | endDrag(); 954 | } 955 | break; 956 | case MotionEvent.ACTION_CANCEL: 957 | if (mIsBeingDragged) { 958 | setCurrentItemInternal(mCurItem, true, true); 959 | mActivePointerId = INVALID_POINTER; 960 | endDrag(); 961 | } 962 | break; 963 | case MotionEventCompat.ACTION_POINTER_DOWN: { 964 | final int index = MotionEventCompat.getActionIndex(ev); 965 | if (mOrientation == HORIZONTAL) { 966 | mLastMotionX = MotionEventCompat.getX(ev, index); 967 | } else { 968 | mLastMotionY = MotionEventCompat.getY(ev, index); 969 | } 970 | mActivePointerId = MotionEventCompat.getPointerId(ev, index); 971 | break; 972 | } 973 | case MotionEventCompat.ACTION_POINTER_UP: 974 | onSecondaryPointerUp(ev); 975 | final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 976 | if (mOrientation == HORIZONTAL) { 977 | mLastMotionX = MotionEventCompat.getX(ev, index); 978 | } else { 979 | mLastMotionY = MotionEventCompat.getY(ev, index); 980 | } 981 | break; 982 | } 983 | return true; 984 | } 985 | 986 | private void onSecondaryPointerUp(MotionEvent ev) { 987 | final int pointerIndex = MotionEventCompat.getActionIndex(ev); 988 | final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); 989 | if (pointerId == mActivePointerId) { 990 | // This was our active pointer going up. Choose a new 991 | // active pointer and adjust accordingly. 992 | final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 993 | if (mOrientation == HORIZONTAL) { 994 | mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); 995 | } else { 996 | mLastMotionY = MotionEventCompat.getY(ev, newPointerIndex); 997 | } 998 | mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); 999 | if (mVelocityTracker != null) { 1000 | mVelocityTracker.clear(); 1001 | } 1002 | } 1003 | } 1004 | 1005 | private void endDrag() { 1006 | mIsBeingDragged = false; 1007 | mIsUnableToDrag = false; 1008 | 1009 | if (mVelocityTracker != null) { 1010 | mVelocityTracker.recycle(); 1011 | mVelocityTracker = null; 1012 | } 1013 | } 1014 | 1015 | private void setScrollingCacheEnabled(boolean enabled) { 1016 | if (mScrollingCacheEnabled != enabled) { 1017 | mScrollingCacheEnabled = enabled; 1018 | if (USE_CACHE) { 1019 | final int size = getChildCount(); 1020 | for (int i = 0; i < size; ++i) { 1021 | final View child = getChildAt(i); 1022 | if (child.getVisibility() != GONE) { 1023 | child.setDrawingCacheEnabled(enabled); 1024 | } 1025 | } 1026 | } 1027 | } 1028 | } 1029 | 1030 | private class PagerObserver extends DataSetObserver { 1031 | @Override 1032 | public void onChanged() { 1033 | dataSetChanged(); 1034 | } 1035 | 1036 | @Override 1037 | public void onInvalidated() { 1038 | dataSetChanged(); 1039 | } 1040 | } 1041 | } 1042 | -------------------------------------------------------------------------------- /TextViewPager/src/co/paulburke/android/textviewpager/ColumnedTextView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpager; 18 | 19 | import android.content.Context; 20 | import android.util.AttributeSet; 21 | import android.util.Log; 22 | import android.widget.LinearLayout; 23 | import android.widget.TextView; 24 | 25 | /** 26 | * Experimental layout that resembles newspaper columns. 27 | * 28 | * @author paulburke (ipaulpro) 29 | */ 30 | public class ColumnedTextView extends LinearLayout { 31 | 32 | protected static final String TAG = "ColumnedTextView"; 33 | 34 | private static final String XML_NS = "http://schemas.android.com/apk/res/android"; 35 | 36 | public interface OnColumnMeasureListener { 37 | public void onColumnMeasure(int[] offsets, int totalColumns, int columnsPerPage); 38 | } 39 | 40 | private static int DEFAULT_COLUMN_COUNT = 2; 41 | private CharSequence mText; 42 | private int mNumColumns = DEFAULT_COLUMN_COUNT; 43 | private OnColumnMeasureListener mListener; 44 | 45 | private PagingLayoutListener.OnPageMeasureListener mOnMeasureListener = new PagingLayoutListener.OnPageMeasureListener() { 46 | @Override 47 | public void onPageMeasure(int[] offsets, int totalLines, int linesPerPage) { 48 | Log.i(TAG, "onPageMeasure offsets count = " + offsets.length + ", totalLines = " 49 | + totalLines + ", linesPerPage = " + linesPerPage); 50 | fillViews(offsets); 51 | } 52 | }; 53 | 54 | public ColumnedTextView(Context context) { 55 | this(context, null); 56 | } 57 | 58 | public ColumnedTextView(Context context, AttributeSet attrs) { 59 | this(context, attrs, 0); 60 | } 61 | 62 | public ColumnedTextView(Context context, AttributeSet attrs, int defStyle) { 63 | super(context, attrs); 64 | 65 | if (attrs != null) { 66 | mNumColumns = attrs.getAttributeIntValue(XML_NS, "numColumns", DEFAULT_COLUMN_COUNT); 67 | mText = attrs.getAttributeValue(XML_NS, "text"); 68 | } 69 | 70 | if (mText != null) { 71 | setText(mText); 72 | } 73 | } 74 | 75 | public void setText(CharSequence text) { 76 | addColumns(); 77 | 78 | mText = text; 79 | TextView textView = (TextView) getChildAt(0); 80 | textView.setText(mText); 81 | } 82 | 83 | public void setText(int resId) { 84 | setText(getContext().getText(resId)); 85 | } 86 | 87 | public int getNumColumns() { 88 | return mNumColumns; 89 | } 90 | 91 | public void setNumColumns(int numColumns) { 92 | mNumColumns = numColumns; 93 | if (mText != null) 94 | setText(mText); 95 | } 96 | 97 | public OnColumnMeasureListener getOnColumnMeasureListener() { 98 | return mListener; 99 | } 100 | 101 | public void setOnColumnMeasureListener(OnColumnMeasureListener listener) { 102 | mListener = listener; 103 | } 104 | 105 | private void addColumns() { 106 | removeAllViews(); 107 | 108 | LayoutParams layoutParams = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1); 109 | layoutParams.setMargins(48, 48, 48, 48); 110 | 111 | TextView textView = new TextView(getContext(), null, R.attr.textViewPagerStyle); 112 | textView.getViewTreeObserver().addOnGlobalLayoutListener( 113 | new PagingLayoutListener(textView, mOnMeasureListener)); 114 | addView(textView, 0, layoutParams); 115 | 116 | for (int i = 1; i < mNumColumns; i++) { 117 | addView(new TextView(getContext(), null, R.attr.textViewPagerStyle), i, layoutParams); 118 | } 119 | } 120 | 121 | private void fillViews(int[] offsets) { 122 | int childCount = getChildCount(); 123 | Log.i(TAG, "onMeasure childCount = " + childCount); 124 | for (int i = 0; i < offsets.length && i < childCount; i++) { 125 | TextView child = (TextView) getChildAt(i); 126 | int start = offsets[i]; 127 | int end = (i < offsets.length - 1) ? offsets[i + 1] : mText.length(); 128 | Log.i(TAG, "onMeasure child " + i + " start = " + start + " end =" + end); 129 | String text = TextViewUtils.getJustifiedText(mText.subSequence(start, end), child); 130 | child.setText(text); 131 | } 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /TextViewPager/src/co/paulburke/android/textviewpager/PagingLayoutListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpager; 18 | 19 | import android.text.Layout; 20 | import android.util.Log; 21 | import android.view.ViewTreeObserver.OnGlobalLayoutListener; 22 | import android.widget.TextView; 23 | 24 | /** 25 | * An {@link OnGlobalLayoutListener} that determines how many "pages" the 26 | * current text should be split into by calculating the maximum number of lines 27 | * that the view can display without clipping.
28 | *
29 | * Set an {@link OnPageMeasureListener} to be notified of the character offsets 30 | * calculated for each page. 31 | * 32 | * @author paulburke (ipaulpro) 33 | */ 34 | public class PagingLayoutListener implements OnGlobalLayoutListener { 35 | 36 | private static final String TAG = "PagingLayoutListener"; 37 | private static final boolean DEBUG = true; 38 | 39 | /** 40 | * Listener used to notify of a completed layout measurement. 41 | */ 42 | public interface OnPageMeasureListener { 43 | /** 44 | * Called when the character offsets have been determined. 45 | * 46 | * @param offsets character offsets for the current text. 47 | * @param totalLines total number of lines in the layout. 48 | * @param linesPerPage number of lines that fit on this view without 49 | * clipping. 50 | */ 51 | public void onPageMeasure(int[] offsets, int totalLines, int linesPerPage); 52 | } 53 | 54 | private TextView mView; 55 | private OnPageMeasureListener mListener; 56 | 57 | /** 58 | * Creates a new PreDrawListener for the given view. 59 | * 60 | * @param view the view to intercept drawing. 61 | * @param listener the {@link OnPageMeasureListener} to listen for offset 62 | * calculations. 63 | */ 64 | public PagingLayoutListener(TextView view, OnPageMeasureListener listener) { 65 | mView = view; 66 | mListener = listener; 67 | } 68 | 69 | @Override 70 | public void onGlobalLayout() { 71 | final Layout layout = mView.getLayout(); 72 | if (layout != null) { 73 | final int height = mView.getHeight() - mView.getPaddingTop() 74 | - mView.getPaddingBottom(); 75 | final int lineCount = layout.getLineCount(); 76 | 77 | // Last visible line 78 | int lastLine = layout.getLineForVertical(height); 79 | // Bottom of the last visible line 80 | int lastLineBottom = layout.getLineBottom(lastLine); 81 | 82 | // Check if the layout is taller than the page 83 | if (lineCount > 0 && lastLineBottom > height) { 84 | // Determine the number of pages needed 85 | int pagesCount = (int) Math.ceil(lineCount / (double) lastLine); 86 | if (DEBUG) Log.d(TAG, "onPreDraw text is too tall! Should be "+pagesCount+" pages."); 87 | 88 | // Determine offsets for each page 89 | int[] offsets = new int[pagesCount]; 90 | for (int i = 0; i < pagesCount; i++) { 91 | offsets[i] = layout.getLineStart(i * lastLine); 92 | if (DEBUG) Log.d(TAG, "onPreDraw new page at " + i + ", starting char offset = " + offsets[i]); 93 | } 94 | 95 | // Clip the text in this view now 96 | CharSequence text = layout.getText().subSequence(0, offsets[1]); 97 | mView.setText(text); 98 | 99 | if (mListener != null) 100 | mListener.onPageMeasure(offsets, lineCount, lastLine); 101 | } 102 | } 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /TextViewPager/src/co/paulburke/android/textviewpager/TextViewPager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpager; 18 | 19 | import android.content.Context; 20 | import android.content.res.TypedArray; 21 | import android.os.Bundle; 22 | import android.os.Parcelable; 23 | import android.support.v4.view.DirectionalViewPager; 24 | import android.support.v4.view.PagerAdapter; 25 | import android.util.AttributeSet; 26 | import android.util.Log; 27 | import android.widget.TextView; 28 | 29 | /** 30 | * A ViewPager that pages the provided text based on the available space. The 31 | * {@link PagerAdapter} is automatically created, as well as the necessary 32 | * {@link TextView}s. You can specify the style to be used by overriding the 33 | * {@link R.attr#textViewPagerStyle} in the Activity Theme, or by specifying a 34 | * layout to be used with {@link #setTextViewLayout(int)}; 35 | * 36 | * @see TextViewPagerAdapter 37 | * @see #setText(CharSequence) 38 | * @see #setText(int) 39 | * @author paulburke (ipaulpro) 40 | */ 41 | public class TextViewPager extends DirectionalViewPager { 42 | 43 | private static final String TAG = "TextViewPager"; 44 | private static final boolean DEBUG = false; 45 | 46 | private static final String INSTANCE_STATE = "instanceState"; 47 | private static final String STATE_OFFSET = "stateToSave"; 48 | 49 | /** 50 | * Listener to be notified of when the adapter has measured and created the 51 | * necessary pages. 52 | */ 53 | public interface OnPageCreatedListener { 54 | /** 55 | * Called when the adapter has measured and created the necessary pages. 56 | * Calls to {@link PagerAdapter#getCount()} will not be correct until 57 | * after this fires. 58 | * 59 | * @param count the total number of pages created. 60 | */ 61 | public void onPageCreated(int count); 62 | } 63 | 64 | private final PagingLayoutListener.OnPageMeasureListener mMeasureListener = new PagingLayoutListener.OnPageMeasureListener() { 65 | @Override 66 | public void onPageMeasure(int[] offsets, int totalLines, int linesPerPage) { 67 | if (DEBUG) Log.i(TAG, "onMeasure pages count = " + offsets.length+", totalLines = "+totalLines+", linesPerPage = "+linesPerPage); 68 | 69 | if (mPagerAdapter != null) { 70 | mPagerAdapter.setOffsets(offsets); 71 | } 72 | 73 | if (mRestoredOffset > 0) { 74 | // Find the restored offset page 75 | for (int i = 0; i < offsets.length; i++) { 76 | if (mRestoredOffset < offsets[i]) { 77 | setCurrentItem(i - 1, false); 78 | break; 79 | } else if (i == offsets.length - 1) { 80 | setCurrentItem(i, false); 81 | } 82 | } 83 | } 84 | 85 | // Let the listener know that new pages were created 86 | if (mPageCreatedListener != null) 87 | mPageCreatedListener.onPageCreated(offsets.length); 88 | } 89 | }; 90 | 91 | private TextViewPagerAdapter mPagerAdapter; 92 | private OnPageCreatedListener mPageCreatedListener; 93 | 94 | private int mRestoredOffset; 95 | 96 | public TextViewPager(Context context) { 97 | this(context, null); 98 | } 99 | 100 | public TextViewPager(Context context, AttributeSet attrs) { 101 | this(context, attrs, R.attr.textViewPagerStyle); 102 | } 103 | 104 | public TextViewPager(Context context, AttributeSet attrs, int defStyle) { 105 | super(context, attrs); 106 | 107 | mPagerAdapter = new TextViewPagerAdapter(context, mMeasureListener); 108 | 109 | if (attrs != null) { 110 | TypedArray attributes = context 111 | .obtainStyledAttributes(attrs, R.styleable.TextViewPager); 112 | 113 | int layout = attributes.getResourceId(R.styleable.TextViewPager_textViewLayout, -1); 114 | CharSequence text = attributes.getText(R.styleable.TextViewPager_android_text); 115 | 116 | mPagerAdapter.setTextViewLayout(layout); 117 | mPagerAdapter.setText(text); 118 | 119 | attributes.recycle(); 120 | } 121 | 122 | setAdapter(mPagerAdapter); 123 | } 124 | 125 | /** 126 | * @param text the text to be paged. 127 | * @attr {@link R.styleable#TextViewPager_android_text} 128 | */ 129 | public void setText(CharSequence text) { 130 | mPagerAdapter.setText(text); 131 | } 132 | 133 | /** 134 | * @param resId the resource identifier of the text to be paged. 135 | * @attr {@link R.styleable#TextViewPager_android_text} 136 | */ 137 | public void setText(int resId) { 138 | mPagerAdapter.setText(getContext().getResources().getText(resId)); 139 | } 140 | 141 | /** 142 | * @param resId the resource identifier of the layout to use for the 143 | * TextView 144 | * @attr {@link R.styleable#TextViewPager_textViewLayout} 145 | */ 146 | public void setTextViewLayout(int resId) { 147 | mPagerAdapter.setTextViewLayout(resId); 148 | } 149 | 150 | /** 151 | * @return the current {@link OnPageCreatedListener}. 152 | */ 153 | public OnPageCreatedListener getOnPageCreatedListener() { 154 | return mPageCreatedListener; 155 | } 156 | 157 | /** 158 | * @param mPageCreatedListener the listener to be notified when the pages 159 | * are created. 160 | */ 161 | public void setOnPageCreatedListener(OnPageCreatedListener mPageCreatedListener) { 162 | this.mPageCreatedListener = mPageCreatedListener; 163 | } 164 | 165 | @Override 166 | public Parcelable onSaveInstanceState() { 167 | 168 | Bundle bundle = new Bundle(); 169 | bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState()); 170 | 171 | // Keep tabs of the current page offset, since the number of lines will 172 | // change with configurations 173 | int offset = mPagerAdapter.getOffsetForPosition(getCurrentItem()); 174 | bundle.putInt(STATE_OFFSET, offset); 175 | 176 | return bundle; 177 | } 178 | 179 | @Override 180 | public void onRestoreInstanceState(Parcelable state) { 181 | 182 | if (state instanceof Bundle) { 183 | Bundle bundle = (Bundle) state; 184 | state = bundle.getParcelable(INSTANCE_STATE); 185 | mRestoredOffset = bundle.getInt(STATE_OFFSET); 186 | } 187 | 188 | super.onRestoreInstanceState(state); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /TextViewPager/src/co/paulburke/android/textviewpager/TextViewPagerAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpager; 18 | 19 | import android.content.Context; 20 | import android.support.v4.view.PagerAdapter; 21 | import android.util.Log; 22 | import android.view.LayoutInflater; 23 | import android.view.View; 24 | import android.view.ViewGroup; 25 | import android.widget.TextView; 26 | 27 | /** 28 | * A {@link PagerAdapter} that creates pages of text based on the available 29 | * space for each view. 30 | * 31 | * @see PagingLayoutListener 32 | * @author paulburke (ipaulpro) 33 | */ 34 | public class TextViewPagerAdapter extends PagerAdapter { 35 | 36 | private static final String TAG = "TextViewPagerAdapter"; 37 | static final boolean DEBUG = false; 38 | 39 | private final Context mContext; 40 | private final PagingLayoutListener.OnPageMeasureListener mMeasureListener; 41 | 42 | private int[] mOffsets = new int[] {}; 43 | 44 | private CharSequence mText; 45 | private int mLayoutRes = -1; 46 | private int mCount = 1; 47 | 48 | LayoutInflater mInflater; 49 | 50 | public TextViewPagerAdapter(Context context, PagingLayoutListener.OnPageMeasureListener listener) { 51 | this(context, listener, null); 52 | } 53 | 54 | public TextViewPagerAdapter(Context context, 55 | PagingLayoutListener.OnPageMeasureListener listener, CharSequence text) { 56 | mContext = context; 57 | mMeasureListener = listener; 58 | mText = text; 59 | 60 | mInflater = LayoutInflater.from(mContext); 61 | } 62 | 63 | @Override 64 | public TextView instantiateItem(final ViewGroup container, final int position) { 65 | TextView view = null; 66 | 67 | if (mLayoutRes > 0) 68 | view = (TextView) mInflater.inflate(mLayoutRes, container, false); 69 | else 70 | view = new TextView(mContext, null, R.attr.textViewPagerStyle); 71 | 72 | if (mText != null) { 73 | int offset = 0; 74 | int end = mText.length(); 75 | int size = mOffsets.length; 76 | 77 | if (size == 0) { 78 | // Add the OnGlobalLayoutListener, which measures the text and 79 | // reports paged character offsets if the text layout is taller 80 | // than the container. 81 | PagingLayoutListener listener = new PagingLayoutListener(view, mMeasureListener); 82 | view.getViewTreeObserver().addOnGlobalLayoutListener(listener); 83 | 84 | } else { 85 | 86 | offset = mOffsets[position]; 87 | int lastPage = size - 1; 88 | 89 | // Don't consider the last page measured, in case there is more 90 | // text to be displayed. 91 | if (position < lastPage) 92 | end = mOffsets[position + 1]; 93 | } 94 | 95 | final CharSequence sub = mText.subSequence(offset, end); 96 | view.setText(sub != null ? sub : mContext.getText(R.string.unable_to_load_text)); 97 | container.addView(view, 0); 98 | 99 | if (DEBUG) Log.d(TAG, "instantiateItem position = " + position + ", offset = " + offset + ", end = " + end + ", text = " + sub); 100 | } 101 | 102 | return view; 103 | } 104 | 105 | @Override 106 | public int getCount() { 107 | return mCount; 108 | } 109 | 110 | @Override 111 | public void destroyItem(ViewGroup container, int position, Object object) { 112 | final View view = (View) object; 113 | container.removeView(view); 114 | } 115 | 116 | @Override 117 | public boolean isViewFromObject(View view, Object object) { 118 | return view == object; 119 | } 120 | 121 | /** 122 | * @return the text that is being displayed. 123 | */ 124 | public CharSequence getText() { 125 | return mText; 126 | } 127 | 128 | /** 129 | * @param text the text to display. 130 | */ 131 | public void setText(CharSequence text) { 132 | if (DEBUG) Log.i(TAG, "setText length = " + text.length()); 133 | mText = text; 134 | notifyDataSetChanged(); 135 | } 136 | 137 | /** 138 | * @return the layout resource identifier used to inflate the TextViews. 139 | */ 140 | public int getTextViewLayout() { 141 | return mLayoutRes; 142 | } 143 | 144 | /** 145 | * @param resId the layout resource identifier to use to inflate the 146 | * TextViews. 147 | */ 148 | public void setTextViewLayout(int resId) { 149 | mLayoutRes = resId; 150 | notifyDataSetChanged(); 151 | } 152 | 153 | /** 154 | * @param offsets array containing the character offsets for each page. 155 | */ 156 | public void setOffsets(int[] offsets) { 157 | mOffsets = offsets; 158 | mCount = mOffsets.length; 159 | notifyDataSetChanged(); 160 | } 161 | 162 | /** 163 | * @return array containing the character offsets for each page. 164 | */ 165 | public int[] getOffsets() { 166 | return mOffsets; 167 | } 168 | 169 | /** 170 | * @param position position in the adapter to get the character offset from. 171 | * @return the character offset from the current page. 172 | */ 173 | public int getOffsetForPosition(int position) { 174 | return mOffsets[position]; 175 | } 176 | 177 | } -------------------------------------------------------------------------------- /TextViewPager/src/co/paulburke/android/textviewpager/TextViewPagerIndicator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Jake Wharton 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 co.paulburke.android.textviewpager; 18 | 19 | import android.content.Context; 20 | import android.content.res.Resources; 21 | import android.content.res.TypedArray; 22 | import android.graphics.Canvas; 23 | import android.graphics.Paint; 24 | import android.graphics.drawable.Drawable; 25 | import android.os.Parcel; 26 | import android.os.Parcelable; 27 | import android.support.v4.view.DirectionalViewPager; 28 | import android.support.v4.view.ViewPager; 29 | import android.util.AttributeSet; 30 | import android.view.MotionEvent; 31 | import android.view.View; 32 | 33 | /** 34 | * Customized UnderlinePageIndicator from the ViewPageIndicator library that 35 | * emulates a scroll bar based on the orientation of the 36 | * {@link DirectionalViewPager} it's connected to. 37 | * 38 | * @author Jake Wharton 39 | * @author paulburke (ipaulpro) Modified to support {@link DirectionalViewPager} 40 | * and better resemble a scroll bar. 41 | */ 42 | public class TextViewPagerIndicator extends View implements ViewPager.OnPageChangeListener { 43 | private static final String TAG = "TextViewPagerIndicator"; 44 | 45 | private static final int FADE_FRAME_MS = 30; 46 | 47 | private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 48 | 49 | private boolean mFades; 50 | private int mFadeDelay; 51 | private int mFadeLength; 52 | private int mFadeBy; 53 | 54 | private DirectionalViewPager mViewPager; 55 | private DirectionalViewPager.OnPageChangeListener mListener; 56 | private int mScrollState; 57 | private int mCurrentPage; 58 | private float mPositionOffset; 59 | 60 | private final Runnable mFadeRunnable = new Runnable() { 61 | @Override 62 | public void run() { 63 | if (!mFades) 64 | return; 65 | 66 | final int alpha = Math.max(mPaint.getAlpha() - mFadeBy, 0); 67 | mPaint.setAlpha(alpha); 68 | setBackgroundAlpha(alpha); 69 | invalidate(); 70 | if (alpha > 0) { 71 | postDelayed(this, FADE_FRAME_MS); 72 | } 73 | } 74 | }; 75 | 76 | public TextViewPagerIndicator(Context context) { 77 | this(context, null); 78 | } 79 | 80 | public TextViewPagerIndicator(Context context, AttributeSet attrs) { 81 | this(context, attrs, R.attr.scrollPageIndicatorStyle); 82 | } 83 | 84 | public TextViewPagerIndicator(Context context, AttributeSet attrs, int defStyle) { 85 | super(context, attrs, defStyle); 86 | if (isInEditMode()) 87 | return; 88 | 89 | final Resources res = getResources(); 90 | 91 | // Load defaults from resources 92 | final boolean defaultFades = res.getBoolean(R.bool.scroll_indicator_fades); 93 | final int defaultFadeDelay = res.getInteger(R.integer.scroll_indicator_fade_delay); 94 | final int defaultFadeLength = res.getInteger(R.integer.scroll_indicator_fade_length); 95 | final int defaultSelectedColor = res.getColor(R.color.scroll_indicator_selected_color); 96 | 97 | // Retrieve styles attributes 98 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewPagerIndicator, 99 | defStyle, 0); 100 | 101 | setFades(a.getBoolean(R.styleable.TextViewPagerIndicator_fades, defaultFades)); 102 | setSelectedColor(a.getColor(R.styleable.TextViewPagerIndicator_selectedColor, 103 | defaultSelectedColor)); 104 | setFadeDelay(a.getInteger(R.styleable.TextViewPagerIndicator_fadeDelay, defaultFadeDelay)); 105 | setFadeLength(a 106 | .getInteger(R.styleable.TextViewPagerIndicator_fadeLength, defaultFadeLength)); 107 | 108 | Drawable background = a.getDrawable(R.styleable.TextViewPagerIndicator_android_background); 109 | if (background != null) 110 | setBackgroundDrawable(background); 111 | 112 | a.recycle(); 113 | } 114 | 115 | public boolean getFades() { 116 | return mFades; 117 | } 118 | 119 | public void setFades(boolean fades) { 120 | if (fades != mFades) { 121 | mFades = fades; 122 | if (fades) { 123 | post(mFadeRunnable); 124 | } else { 125 | removeCallbacks(mFadeRunnable); 126 | mPaint.setAlpha(0xFF); 127 | setBackgroundAlpha(0xFF); 128 | invalidate(); 129 | } 130 | } 131 | } 132 | 133 | public int getFadeDelay() { 134 | return mFadeDelay; 135 | } 136 | 137 | public void setFadeDelay(int fadeDelay) { 138 | mFadeDelay = fadeDelay; 139 | } 140 | 141 | public int getFadeLength() { 142 | return mFadeLength; 143 | } 144 | 145 | public void setFadeLength(int fadeLength) { 146 | mFadeLength = fadeLength; 147 | mFadeBy = 0xFF / (mFadeLength / FADE_FRAME_MS); 148 | } 149 | 150 | public int getSelectedColor() { 151 | return mPaint.getColor(); 152 | } 153 | 154 | public void setSelectedColor(int selectedColor) { 155 | mPaint.setColor(selectedColor); 156 | invalidate(); 157 | } 158 | 159 | @Override 160 | protected void onDraw(Canvas canvas) { 161 | super.onDraw(canvas); 162 | 163 | if (mViewPager == null) 164 | return; 165 | 166 | final int count = mViewPager.getAdapter().getCount(); 167 | if (count == 0) 168 | return; 169 | 170 | if (mCurrentPage >= count) { 171 | setCurrentItem(count - 1); 172 | return; 173 | } 174 | 175 | float left = 0f, top = 0f, right = 0f, bottom = 0f; 176 | 177 | final int paddingTop = getPaddingTop(); 178 | final int paddingBottom = getPaddingBottom(); 179 | final int paddingRight = getPaddingRight(); 180 | final int paddingLeft = getPaddingLeft(); 181 | 182 | if (isHorizontal()) { 183 | final float pageWidth = (getWidth() - paddingLeft - paddingRight) / (1f * count); 184 | left = paddingLeft + pageWidth * (mCurrentPage + mPositionOffset); 185 | right = left + pageWidth; 186 | top = 0f; 187 | bottom = getHeight(); 188 | } 189 | else if (isVertical()) { 190 | final float pageHeight = (getHeight() - paddingTop - paddingBottom) / (1f * count); 191 | top = paddingTop + pageHeight * (mCurrentPage + mPositionOffset); 192 | bottom = top + pageHeight; 193 | left = 0f; 194 | right = getWidth(); 195 | } 196 | 197 | canvas.drawRect(left, top, right, bottom, mPaint); 198 | } 199 | 200 | private boolean isHorizontal() { 201 | return mViewPager.getOrientation() == DirectionalViewPager.HORIZONTAL; 202 | } 203 | 204 | private boolean isVertical() { 205 | return mViewPager.getOrientation() == DirectionalViewPager.VERTICAL; 206 | } 207 | 208 | public void setViewPager(ViewPager viewPager) { 209 | if (mViewPager == viewPager) { 210 | return; 211 | } 212 | if (mViewPager != null) { 213 | // Clear us from the old pager. 214 | mViewPager.setOnPageChangeListener(null); 215 | } 216 | if (viewPager.getAdapter() == null) { 217 | throw new IllegalStateException("ViewPager does not have adapter instance."); 218 | } 219 | mViewPager = (DirectionalViewPager) viewPager; 220 | mViewPager.setOnPageChangeListener(this); 221 | mViewPager.setOnTouchListener(new OnTouchListener() { 222 | @Override 223 | public boolean onTouch(View v, MotionEvent event) { 224 | if (event.getAction() == MotionEvent.ACTION_DOWN) { 225 | show(); 226 | } 227 | return false; 228 | } 229 | }); 230 | invalidate(); 231 | post(new Runnable() { 232 | @Override 233 | public void run() { 234 | if (mFades) { 235 | post(mFadeRunnable); 236 | } 237 | } 238 | }); 239 | } 240 | 241 | public void show() { 242 | removeCallbacks(mFadeRunnable); 243 | mPaint.setAlpha(0xFF); 244 | setBackgroundAlpha(0xFF); 245 | postDelayed(mFadeRunnable, mFadeDelay); 246 | } 247 | 248 | public void hide() { 249 | removeCallbacks(mFadeRunnable); 250 | post(mFadeRunnable); 251 | } 252 | 253 | public void setViewPager(ViewPager view, int initialPosition) { 254 | setViewPager(view); 255 | setCurrentItem(initialPosition); 256 | } 257 | 258 | public void setCurrentItem(int item) { 259 | if (mViewPager == null) { 260 | throw new IllegalStateException("ViewPager has not been bound."); 261 | } 262 | mViewPager.setCurrentItem(item); 263 | mCurrentPage = item; 264 | invalidate(); 265 | } 266 | 267 | public void notifyDataSetChanged() { 268 | invalidate(); 269 | } 270 | 271 | @Override 272 | public void onPageScrollStateChanged(int state) { 273 | mScrollState = state; 274 | 275 | if (mListener != null) { 276 | mListener.onPageScrollStateChanged(state); 277 | } 278 | } 279 | 280 | @Override 281 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 282 | mCurrentPage = position; 283 | mPositionOffset = positionOffset; 284 | if (mFades) { 285 | if (positionOffsetPixels > 0) { 286 | removeCallbacks(mFadeRunnable); 287 | mPaint.setAlpha(0xFF); 288 | setBackgroundAlpha(0xFF); 289 | } else if (mScrollState != ViewPager.SCROLL_STATE_DRAGGING) { 290 | postDelayed(mFadeRunnable, mFadeDelay); 291 | } 292 | } 293 | invalidate(); 294 | 295 | if (mListener != null) { 296 | mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); 297 | } 298 | } 299 | 300 | @Override 301 | public void onPageSelected(int position) { 302 | if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { 303 | mCurrentPage = position; 304 | mPositionOffset = 0; 305 | invalidate(); 306 | mFadeRunnable.run(); 307 | } 308 | if (mListener != null) { 309 | mListener.onPageSelected(position); 310 | } 311 | } 312 | 313 | public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { 314 | mListener = listener; 315 | } 316 | 317 | private void setBackgroundAlpha(int alpha) { 318 | Drawable background = getBackground(); 319 | if (background != null) 320 | background.setAlpha(alpha); 321 | } 322 | 323 | @Override 324 | public void onRestoreInstanceState(Parcelable state) { 325 | SavedState savedState = (SavedState) state; 326 | super.onRestoreInstanceState(savedState.getSuperState()); 327 | mCurrentPage = savedState.currentPage; 328 | requestLayout(); 329 | } 330 | 331 | @Override 332 | public Parcelable onSaveInstanceState() { 333 | Parcelable superState = super.onSaveInstanceState(); 334 | SavedState savedState = new SavedState(superState); 335 | savedState.currentPage = mCurrentPage; 336 | return savedState; 337 | } 338 | 339 | static class SavedState extends BaseSavedState { 340 | int currentPage; 341 | 342 | public SavedState(Parcelable superState) { 343 | super(superState); 344 | } 345 | 346 | private SavedState(Parcel in) { 347 | super(in); 348 | currentPage = in.readInt(); 349 | } 350 | 351 | @Override 352 | public void writeToParcel(Parcel dest, int flags) { 353 | super.writeToParcel(dest, flags); 354 | dest.writeInt(currentPage); 355 | } 356 | 357 | public static final Creator CREATOR = new Creator() { 358 | @Override 359 | public SavedState createFromParcel(Parcel in) { 360 | return new SavedState(in); 361 | } 362 | 363 | @Override 364 | public SavedState[] newArray(int size) { 365 | return new SavedState[size]; 366 | } 367 | }; 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /TextViewPager/src/co/paulburke/android/textviewpager/TextViewUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpager; 18 | 19 | import android.graphics.Paint; 20 | import android.text.TextUtils; 21 | import android.widget.TextView; 22 | 23 | import java.util.ArrayList; 24 | 25 | /** 26 | * Experimental 27 | */ 28 | public class TextViewUtils { 29 | 30 | private static final String TAG = "TextViewUtils"; 31 | 32 | private TextViewUtils() { 33 | } 34 | 35 | /** 36 | * Not ready for prime time. 37 | */ 38 | public static String getJustifiedText(CharSequence text, TextView view) { 39 | ArrayList lineList = lineBreak(String.valueOf(text), view.getPaint(), 40 | view.getLayout().getWidth()); 41 | 42 | return TextUtils.join(" ", lineList).replaceFirst("\\s", ""); 43 | } 44 | 45 | /** 46 | * TODO Respect \n 47 | */ 48 | private static ArrayList lineBreak(String text, Paint paint, float contentWidth) { 49 | String[] wordArray = text.split("\\s"); 50 | ArrayList lineList = new ArrayList(); 51 | String myText = ""; 52 | 53 | for (String word : wordArray) { 54 | if (paint.measureText(myText + " " + word) <= contentWidth) 55 | myText = myText + " " + word; 56 | else { 57 | int totalSpacesToInsert = (int) ((contentWidth - paint.measureText(myText)) / paint 58 | .measureText(" ")); 59 | lineList.add(justifyLine(myText, totalSpacesToInsert)); 60 | myText = word; 61 | } 62 | } 63 | lineList.add(myText); 64 | return lineList; 65 | } 66 | 67 | private static String justifyLine(String text, int totalSpacesToInsert) { 68 | String[] wordArray = text.split("\\s"); 69 | String toAppend = " "; 70 | 71 | while (totalSpacesToInsert >= wordArray.length - 1 && wordArray.length > 1) { 72 | toAppend = toAppend + " "; 73 | totalSpacesToInsert = totalSpacesToInsert - (wordArray.length - 1); 74 | } 75 | int i = 0; 76 | String justifiedText = ""; 77 | for (String word : wordArray) { 78 | if (i < totalSpacesToInsert) 79 | justifiedText = justifiedText + word + " " + toAppend; 80 | 81 | else 82 | justifiedText = justifiedText + word + toAppend; 83 | 84 | i++; 85 | } 86 | 87 | return justifiedText; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /TextViewPagerExample/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 21 | 22 | 25 | 26 | 32 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /TextViewPagerExample/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /TextViewPagerExample/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-19 15 | android.library.reference.1=../TextViewPager 16 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iPaulPro/Android-TextViewPager/3b8af8090b441610f327a367ec0d7a1f32f68e54/TextViewPagerExample/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /TextViewPagerExample/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iPaulPro/Android-TextViewPager/3b8af8090b441610f327a367ec0d7a1f32f68e54/TextViewPagerExample/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /TextViewPagerExample/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iPaulPro/Android-TextViewPager/3b8af8090b441610f327a367ec0d7a1f32f68e54/TextViewPagerExample/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /TextViewPagerExample/res/layout/activity_styled_vertical.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 34 | 35 | 44 | 45 | 52 | 53 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/layout/text.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 21 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values-sw300dp-land/integers.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 2 19 | 20 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values-sw600dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 23 | 48dp 24 | 48dp 25 | 26 | 27 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values-sw600dp/integers.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 2 19 | 20 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values-sw720dp-land/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 23 | 48dp 24 | 128dp 25 | 26 | 27 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values-sw720dp-land/integers.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 17 | 18 | 19 | 3 20 | 21 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values-v11/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 23 | 26 | 27 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 24dp 20 | 24dp 21 | 22 | 23 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values/integers.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 1 19 | 20 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | TextViewPager 20 |     But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?\n\n    On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.\n\n    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\n\n    At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. 21 | Page %1$d of %2$d 22 | 23 | 24 | Basic horizontal 25 | Styled vertical 26 | Columned (Experimental) 27 | 28 | 29 | -------------------------------------------------------------------------------- /TextViewPagerExample/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 23 | 30 | 31 | 32 | 38 | 39 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /TextViewPagerExample/src/co/paulburke/android/textviewpagerexample/BasicHorizontalActivity.java: -------------------------------------------------------------------------------- 1 | 2 | package co.paulburke.android.textviewpagerexample; 3 | 4 | import android.app.Activity; 5 | import android.os.Bundle; 6 | 7 | import co.paulburke.android.textviewpager.TextViewPager; 8 | 9 | public class BasicHorizontalActivity extends Activity { 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | 15 | TextViewPager pager = new TextViewPager(this); 16 | // Needed for restoring state 17 | pager.setId(R.id.pager); 18 | // Set the text on the pager, itself 19 | pager.setText(R.string.lipsum); 20 | 21 | setContentView(pager); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /TextViewPagerExample/src/co/paulburke/android/textviewpagerexample/ColumnsActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpagerexample; 18 | 19 | import android.app.Activity; 20 | import android.os.Bundle; 21 | 22 | import co.paulburke.android.textviewpager.ColumnedTextView; 23 | 24 | public class ColumnsActivity extends Activity { 25 | 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | 30 | ColumnedTextView view = new ColumnedTextView(this); 31 | view.setNumColumns(getResources().getInteger(R.integer.num_columns)); 32 | view.setText(R.string.lipsum); 33 | setContentView(view); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /TextViewPagerExample/src/co/paulburke/android/textviewpagerexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpagerexample; 18 | 19 | import android.app.ListActivity; 20 | import android.content.Intent; 21 | import android.os.Bundle; 22 | import android.view.View; 23 | import android.widget.ArrayAdapter; 24 | import android.widget.ListView; 25 | 26 | public class MainActivity extends ListActivity { 27 | 28 | @Override 29 | protected void onCreate(Bundle savedInstanceState) { 30 | super.onCreate(savedInstanceState); 31 | 32 | setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, 33 | getResources().getStringArray(R.array.main_list_items))); 34 | } 35 | 36 | @Override 37 | protected void onListItemClick(ListView l, View v, int position, long id) { 38 | 39 | switch (position) { 40 | case 0: 41 | startActivity(new Intent(this, BasicHorizontalActivity.class)); 42 | break; 43 | 44 | case 1: 45 | startActivity(new Intent(this, StyledVerticalActivity.class)); 46 | break; 47 | 48 | case 2: 49 | startActivity(new Intent(this, ColumnsActivity.class)); 50 | break; 51 | } 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /TextViewPagerExample/src/co/paulburke/android/textviewpagerexample/StyledVerticalActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Paul Burke 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 co.paulburke.android.textviewpagerexample; 18 | 19 | import android.app.Activity; 20 | import android.os.Bundle; 21 | import android.support.v4.view.ViewPager.SimpleOnPageChangeListener; 22 | import android.widget.TextView; 23 | 24 | import co.paulburke.android.textviewpager.TextViewPager; 25 | import co.paulburke.android.textviewpager.TextViewPager.OnPageCreatedListener; 26 | import co.paulburke.android.textviewpager.TextViewPagerIndicator; 27 | 28 | public class StyledVerticalActivity extends Activity { 29 | 30 | private TextView mNumber; 31 | private TextViewPager mPager; 32 | 33 | @Override 34 | protected void onCreate(Bundle savedInstanceState) { 35 | super.onCreate(savedInstanceState); 36 | 37 | setContentView(R.layout.activity_styled_vertical); 38 | 39 | mNumber = (TextView) findViewById(R.id.page_number); 40 | 41 | mPager = (TextViewPager) findViewById(R.id.pager); 42 | // We don't know how many pages there are until we've measured 43 | mPager.setOnPageCreatedListener(new OnPageCreatedListener() { 44 | @Override 45 | public void onPageCreated(int count) { 46 | setPageNumber(mPager.getCurrentItem()); 47 | } 48 | }); 49 | 50 | final TextViewPagerIndicator indicator = (TextViewPagerIndicator) findViewById(R.id.indicator); 51 | indicator.setViewPager(mPager); 52 | // If not using an indicator, you'd set this on the TextViewPager itself 53 | indicator.setOnPageChangeListener(new SimpleOnPageChangeListener() { 54 | @Override 55 | public void onPageSelected(int position) { 56 | setPageNumber(position); 57 | } 58 | }); 59 | } 60 | 61 | private void setPageNumber(int position) { 62 | mNumber.setText(getString(R.string.page_number, position + 1, 63 | mPager.getAdapter().getCount())); 64 | } 65 | } 66 | --------------------------------------------------------------------------------