116 |
117 |
--------------------------------------------------------------------------------
/sample/src/main/java/me/relex/circleindicator/sample/SampleActivity.java:
--------------------------------------------------------------------------------
1 | package me.relex.circleindicator.sample;
2 |
3 | import android.os.Bundle;
4 | import android.view.LayoutInflater;
5 | import android.view.View;
6 | import android.view.ViewGroup;
7 | import android.widget.TextView;
8 | import androidx.annotation.NonNull;
9 | import androidx.annotation.Nullable;
10 | import androidx.appcompat.app.ActionBar;
11 | import androidx.appcompat.app.AppCompatActivity;
12 | import androidx.appcompat.widget.Toolbar;
13 | import androidx.fragment.app.Fragment;
14 | import androidx.fragment.app.FragmentTransaction;
15 | import androidx.recyclerview.widget.LinearLayoutManager;
16 | import androidx.recyclerview.widget.RecyclerView;
17 | import java.util.ArrayList;
18 | import java.util.List;
19 | import me.relex.circleindicator.sample.fragment.ChangeDrawableFragment;
20 | import me.relex.circleindicator.sample.fragment.CustomAnimationFragment;
21 | import me.relex.circleindicator.sample.fragment.DefaultFragment;
22 | import me.relex.circleindicator.sample.fragment.DynamicAdapterFragment;
23 | import me.relex.circleindicator.sample.fragment.LoopRecyclerViewFragment;
24 | import me.relex.circleindicator.sample.fragment.LoopViewPagerFragment;
25 | import me.relex.circleindicator.sample.fragment.RecyclerViewFragment;
26 | import me.relex.circleindicator.sample.fragment.ResetAdapterFragment;
27 | import me.relex.circleindicator.sample.fragment.SnackbarBehaviorFragment;
28 | import me.relex.circleindicator.sample.fragment.ViewPager2Fragment;
29 |
30 | public class SampleActivity extends AppCompatActivity {
31 |
32 | @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 |
35 | setContentView(R.layout.activity_sample);
36 |
37 | initToolbar();
38 |
39 | Fragment demoFragment = getSupportFragmentManager().getFragmentFactory()
40 | .instantiate(getClassLoader(), SampleListFragment.class.getName());
41 | FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
42 | fragmentTransaction.replace(R.id.fragment_container, demoFragment);
43 | fragmentTransaction.commit();
44 |
45 | getSupportFragmentManager().addOnBackStackChangedListener(() -> {
46 | int count = getSupportFragmentManager().getBackStackEntryCount();
47 | ActionBar actionbar = getSupportActionBar();
48 | if (actionbar != null) {
49 | actionbar.setDisplayHomeAsUpEnabled(count > 0);
50 | actionbar.setDisplayShowHomeEnabled(count > 0);
51 | }
52 | });
53 | }
54 |
55 | private void initToolbar() {
56 | Toolbar toolbar = findViewById(R.id.toolbar);
57 | setSupportActionBar(toolbar);
58 | toolbar.setNavigationOnClickListener(v -> onBackPressed());
59 | }
60 |
61 | public static class SampleListFragment extends Fragment {
62 |
63 | @Nullable @Override
64 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
65 | @Nullable Bundle savedInstanceState) {
66 | return new RecyclerView(getContext());
67 | }
68 |
69 | @Override
70 | public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
71 | SampleListAdapter adapter = new SampleListAdapter();
72 |
73 | RecyclerView recyclerView = (RecyclerView) view;
74 | recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
75 | recyclerView.setAdapter(adapter);
76 |
77 | adapter.add(new SampleInfo("Default", DefaultFragment.class.getName()));
78 | adapter.add(
79 | new SampleInfo("Custom Animation", CustomAnimationFragment.class.getName()));
80 | adapter.add(new SampleInfo("Change Drawable", ChangeDrawableFragment.class.getName()));
81 | adapter.add(new SampleInfo("Dynamic Adapter", DynamicAdapterFragment.class.getName()));
82 | adapter.add(new SampleInfo("Reset Adapter", ResetAdapterFragment.class.getName()));
83 | adapter.add(new SampleInfo("LoopViewPager", LoopViewPagerFragment.class.getName()));
84 | adapter.add(
85 | new SampleInfo("Snackbar Behavior", SnackbarBehaviorFragment.class.getName()));
86 | adapter.add(new SampleInfo("RecyclerView (CircleIndicator2)",
87 | RecyclerViewFragment.class.getName()));
88 | adapter.add(new SampleInfo("LoopRecyclerView (CircleIndicator2) and Manual control",
89 | LoopRecyclerViewFragment.class.getName()));
90 | adapter.add(new SampleInfo("AndroidX ViewPager2 (CircleIndicator3)",
91 | ViewPager2Fragment.class.getName()));
92 | }
93 |
94 | private class SampleListAdapter extends RecyclerView.Adapter {
95 |
96 | private final List mList = new ArrayList<>();
97 |
98 | @NonNull @Override
99 | public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
100 | return ItemViewHolder.create(parent);
101 | }
102 |
103 | @Override
104 | public void onBindViewHolder(@NonNull final ItemViewHolder holder, int position) {
105 | SampleInfo sample = mList.get(position);
106 | holder.bindView(sample.title);
107 | holder.itemView.setOnClickListener(new View.OnClickListener() {
108 | @Override public void onClick(View v) {
109 | navigateToFragment(mList.get(holder.getAdapterPosition()).fragmentName);
110 | }
111 | });
112 | }
113 |
114 | @Override public int getItemCount() {
115 | return mList.size();
116 | }
117 |
118 | public boolean add(SampleInfo object) {
119 | int lastIndex = mList.size();
120 | if (mList.add(object)) {
121 | notifyItemInserted(lastIndex);
122 | return true;
123 | } else {
124 | return false;
125 | }
126 | }
127 | }
128 |
129 | private void navigateToFragment(String fragmentName) {
130 | Fragment fragment = getFragmentManager().getFragmentFactory()
131 | .instantiate(getContext().getClassLoader(), fragmentName);
132 | FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
133 |
134 | fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out,
135 | android.R.anim.fade_in, android.R.anim.fade_out);
136 | fragmentTransaction.replace(R.id.fragment_container, fragment);
137 | fragmentTransaction.addToBackStack(fragmentName);
138 | fragmentTransaction.commit();
139 | }
140 |
141 | private static class ItemViewHolder extends RecyclerView.ViewHolder {
142 | ItemViewHolder(View itemView) {
143 | super(itemView);
144 | }
145 |
146 | void bindView(String title) {
147 | ((TextView) itemView).setText(title);
148 | }
149 |
150 | static ItemViewHolder create(ViewGroup viewGroup) {
151 | return new ItemViewHolder(LayoutInflater.from(viewGroup.getContext())
152 | .inflate(R.layout.item_view, viewGroup, false));
153 | }
154 | }
155 |
156 | private static class SampleInfo {
157 | public final String title;
158 | final String fragmentName;
159 |
160 | SampleInfo(String title, String fragmentName) {
161 | this.title = title;
162 | this.fragmentName = fragmentName;
163 | }
164 | }
165 | }
166 | }
167 |
--------------------------------------------------------------------------------
/LoopingViewPager/src/main/java/com/imbryk/viewPager/LoopViewPager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Leszek Mzyk
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 | package com.imbryk.viewPager;
17 |
18 | import android.content.Context;
19 | import android.util.AttributeSet;
20 | import androidx.annotation.NonNull;
21 | import androidx.viewpager.widget.PagerAdapter;
22 | import androidx.viewpager.widget.ViewPager;
23 | import java.util.ArrayList;
24 | import java.util.List;
25 |
26 | public class LoopViewPager extends ViewPager {
27 | private static final boolean DEFAULT_BOUNDARY_CASHING = false;
28 | private static final boolean DEFAULT_BOUNDARY_LOOPING = true;
29 |
30 | private LoopPagerAdapterWrapper mAdapter;
31 | private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING;
32 | private boolean mBoundaryLooping = DEFAULT_BOUNDARY_LOOPING;
33 | private List mOnPageChangeListeners;
34 |
35 | /**
36 | * helper function which may be used when implementing FragmentPagerAdapter
37 | *
38 | * @return (position - 1)%count
39 | */
40 | public static int toRealPosition(int position, int count) {
41 | position = position - 1;
42 | if (position < 0) {
43 | position += count;
44 | } else {
45 | position = position % count;
46 | }
47 | return position;
48 | }
49 |
50 | /**
51 | * If set to true, the boundary views (i.e. first and last) will never be
52 | * destroyed This may help to prevent "blinking" of some views
53 | */
54 | public void setBoundaryCaching(boolean flag) {
55 | mBoundaryCaching = flag;
56 | if (mAdapter != null) {
57 | mAdapter.setBoundaryCaching(flag);
58 | }
59 | }
60 |
61 | public void setBoundaryLooping(boolean flag) {
62 | mBoundaryLooping = flag;
63 | if (mAdapter != null) {
64 | mAdapter.setBoundaryLooping(flag);
65 | }
66 | }
67 |
68 | @Override public void setAdapter(PagerAdapter adapter) {
69 | mAdapter = new LoopPagerAdapterWrapper(adapter);
70 | mAdapter.setBoundaryCaching(mBoundaryCaching);
71 | mAdapter.setBoundaryLooping(mBoundaryLooping);
72 | super.setAdapter(mAdapter);
73 | setCurrentItem(0, false);
74 | }
75 |
76 | @Override public PagerAdapter getAdapter() {
77 | return mAdapter != null ? mAdapter.getRealAdapter() : null;
78 | }
79 |
80 | @Override public int getCurrentItem() {
81 | return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : 0;
82 | }
83 |
84 | @Override public void setCurrentItem(int item, boolean smoothScroll) {
85 | int realItem = mAdapter.toInnerPosition(item);
86 | super.setCurrentItem(realItem, smoothScroll);
87 | }
88 |
89 | @Override public void setCurrentItem(int item) {
90 | if (getCurrentItem() != item) {
91 | setCurrentItem(item, true);
92 | }
93 | }
94 |
95 | @Override public void addOnPageChangeListener(@NonNull OnPageChangeListener listener) {
96 | if (mOnPageChangeListeners == null) {
97 | mOnPageChangeListeners = new ArrayList<>();
98 | }
99 | mOnPageChangeListeners.add(listener);
100 | }
101 |
102 | @Override public void removeOnPageChangeListener(@NonNull OnPageChangeListener listener) {
103 | if (mOnPageChangeListeners != null) {
104 | mOnPageChangeListeners.remove(listener);
105 | }
106 | }
107 |
108 | @Override public void clearOnPageChangeListeners() {
109 | if (mOnPageChangeListeners != null) {
110 | mOnPageChangeListeners.clear();
111 | }
112 | }
113 |
114 | public LoopViewPager(Context context) {
115 | super(context);
116 | init(context);
117 | }
118 |
119 | public LoopViewPager(Context context, AttributeSet attrs) {
120 | super(context, attrs);
121 | init(context);
122 | }
123 |
124 | private void init(Context context) {
125 | super.removeOnPageChangeListener(onPageChangeListener);
126 | super.addOnPageChangeListener(onPageChangeListener);
127 | }
128 |
129 | private final OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
130 | private float mPreviousOffset = -1;
131 | private float mPreviousPosition = -1;
132 |
133 | @Override public void onPageSelected(int position) {
134 |
135 | int realPosition = mAdapter.toRealPosition(position);
136 | if (mPreviousPosition != realPosition) {
137 | mPreviousPosition = realPosition;
138 |
139 | if (mOnPageChangeListeners != null) {
140 | for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
141 | OnPageChangeListener listener = mOnPageChangeListeners.get(i);
142 | if (listener != null) {
143 | listener.onPageSelected(realPosition);
144 | }
145 | }
146 | }
147 | }
148 | }
149 |
150 | @Override
151 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
152 | int realPosition = position;
153 | if (mAdapter != null) {
154 | realPosition = mAdapter.toRealPosition(position);
155 |
156 | if (positionOffset == 0 && mPreviousOffset == 0 && (position == 0
157 | || position == mAdapter.getCount() - 1)) {
158 | setCurrentItem(realPosition, false);
159 | }
160 | }
161 |
162 | mPreviousOffset = positionOffset;
163 |
164 | if (mOnPageChangeListeners != null) {
165 | for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
166 | OnPageChangeListener listener = mOnPageChangeListeners.get(i);
167 | if (listener != null) {
168 | if (realPosition != mAdapter.getRealCount() - 1) {
169 | listener.onPageScrolled(realPosition, positionOffset,
170 | positionOffsetPixels);
171 | } else {
172 | if (positionOffset > .5) {
173 | listener.onPageScrolled(0, 0, 0);
174 | } else {
175 | listener.onPageScrolled(realPosition, 0, 0);
176 | }
177 | }
178 | }
179 | }
180 | }
181 | }
182 |
183 | @Override public void onPageScrollStateChanged(int state) {
184 | if (mAdapter != null) {
185 | int position = LoopViewPager.super.getCurrentItem();
186 | int realPosition = mAdapter.toRealPosition(position);
187 | if (state == ViewPager.SCROLL_STATE_IDLE && (position == 0
188 | || position == mAdapter.getCount() - 1)) {
189 | setCurrentItem(realPosition, false);
190 | }
191 | }
192 |
193 | if (mOnPageChangeListeners != null) {
194 | for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
195 | OnPageChangeListener listener = mOnPageChangeListeners.get(i);
196 | if (listener != null) {
197 | listener.onPageScrollStateChanged(state);
198 | }
199 | }
200 | }
201 | }
202 | };
203 | }
204 |
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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 |
--------------------------------------------------------------------------------
/circleindicator/src/main/java/me/relex/circleindicator/BaseCircleIndicator.java:
--------------------------------------------------------------------------------
1 | package me.relex.circleindicator;
2 |
3 | import android.animation.Animator;
4 | import android.animation.AnimatorInflater;
5 | import android.annotation.TargetApi;
6 | import android.content.Context;
7 | import android.content.res.ColorStateList;
8 | import android.content.res.TypedArray;
9 | import android.graphics.drawable.Drawable;
10 | import android.os.Build;
11 | import android.util.AttributeSet;
12 | import android.util.TypedValue;
13 | import android.view.Gravity;
14 | import android.view.View;
15 | import android.view.animation.Interpolator;
16 | import android.widget.LinearLayout;
17 | import androidx.annotation.ColorInt;
18 | import androidx.annotation.DrawableRes;
19 | import androidx.annotation.Nullable;
20 | import androidx.core.content.ContextCompat;
21 | import androidx.core.graphics.drawable.DrawableCompat;
22 | import androidx.core.view.ViewCompat;
23 |
24 | class BaseCircleIndicator extends LinearLayout {
25 |
26 | private final static int DEFAULT_INDICATOR_WIDTH = 5;
27 |
28 | protected int mIndicatorMargin = -1;
29 | protected int mIndicatorWidth = -1;
30 | protected int mIndicatorHeight = -1;
31 |
32 | protected int mIndicatorBackgroundResId;
33 | protected int mIndicatorUnselectedBackgroundResId;
34 |
35 | protected ColorStateList mIndicatorTintColor;
36 | protected ColorStateList mIndicatorTintUnselectedColor;
37 |
38 | protected Animator mAnimatorOut;
39 | protected Animator mAnimatorIn;
40 | protected Animator mImmediateAnimatorOut;
41 | protected Animator mImmediateAnimatorIn;
42 |
43 | protected int mLastPosition = -1;
44 |
45 | @Nullable private IndicatorCreatedListener mIndicatorCreatedListener;
46 |
47 | public BaseCircleIndicator(Context context) {
48 | super(context);
49 | init(context, null);
50 | }
51 |
52 | public BaseCircleIndicator(Context context, AttributeSet attrs) {
53 | super(context, attrs);
54 | init(context, attrs);
55 | }
56 |
57 | public BaseCircleIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
58 | super(context, attrs, defStyleAttr);
59 | init(context, attrs);
60 | }
61 |
62 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
63 | public BaseCircleIndicator(Context context, AttributeSet attrs, int defStyleAttr,
64 | int defStyleRes) {
65 | super(context, attrs, defStyleAttr, defStyleRes);
66 | init(context, attrs);
67 | }
68 |
69 | private void init(Context context, AttributeSet attrs) {
70 | Config config = handleTypedArray(context, attrs);
71 | initialize(config);
72 |
73 | if (isInEditMode()) {
74 | createIndicators(3, 1);
75 | }
76 | }
77 |
78 | private Config handleTypedArray(Context context, AttributeSet attrs) {
79 | Config config = new Config();
80 | if (attrs == null) {
81 | return config;
82 | }
83 | TypedArray typedArray =
84 | context.obtainStyledAttributes(attrs, R.styleable.BaseCircleIndicator);
85 | config.width =
86 | typedArray.getDimensionPixelSize(R.styleable.BaseCircleIndicator_ci_width, -1);
87 | config.height =
88 | typedArray.getDimensionPixelSize(R.styleable.BaseCircleIndicator_ci_height, -1);
89 | config.margin =
90 | typedArray.getDimensionPixelSize(R.styleable.BaseCircleIndicator_ci_margin, -1);
91 | config.animatorResId = typedArray.getResourceId(R.styleable.BaseCircleIndicator_ci_animator,
92 | R.animator.scale_with_alpha);
93 | config.animatorReverseResId =
94 | typedArray.getResourceId(R.styleable.BaseCircleIndicator_ci_animator_reverse, 0);
95 | config.backgroundResId =
96 | typedArray.getResourceId(R.styleable.BaseCircleIndicator_ci_drawable,
97 | R.drawable.white_radius);
98 | config.unselectedBackgroundId =
99 | typedArray.getResourceId(R.styleable.BaseCircleIndicator_ci_drawable_unselected,
100 | config.backgroundResId);
101 | config.orientation = typedArray.getInt(R.styleable.BaseCircleIndicator_ci_orientation, -1);
102 | config.gravity = typedArray.getInt(R.styleable.BaseCircleIndicator_ci_gravity, -1);
103 | typedArray.recycle();
104 |
105 | return config;
106 | }
107 |
108 | public void initialize(Config config) {
109 | int miniSize = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
110 | DEFAULT_INDICATOR_WIDTH, getResources().getDisplayMetrics()) + 0.5f);
111 | mIndicatorWidth = (config.width < 0) ? miniSize : config.width;
112 | mIndicatorHeight = (config.height < 0) ? miniSize : config.height;
113 | mIndicatorMargin = (config.margin < 0) ? miniSize : config.margin;
114 |
115 | mAnimatorOut = createAnimatorOut(config);
116 | mImmediateAnimatorOut = createAnimatorOut(config);
117 | mImmediateAnimatorOut.setDuration(0);
118 |
119 | mAnimatorIn = createAnimatorIn(config);
120 | mImmediateAnimatorIn = createAnimatorIn(config);
121 | mImmediateAnimatorIn.setDuration(0);
122 |
123 | mIndicatorBackgroundResId =
124 | (config.backgroundResId == 0) ? R.drawable.white_radius : config.backgroundResId;
125 | mIndicatorUnselectedBackgroundResId =
126 | (config.unselectedBackgroundId == 0) ? config.backgroundResId
127 | : config.unselectedBackgroundId;
128 |
129 | setOrientation(config.orientation == VERTICAL ? VERTICAL : HORIZONTAL);
130 | setGravity(config.gravity >= 0 ? config.gravity : Gravity.CENTER);
131 | }
132 |
133 | public void tintIndicator(@ColorInt int indicatorColor) {
134 | tintIndicator(indicatorColor, indicatorColor);
135 | }
136 |
137 | public void tintIndicator(@ColorInt int indicatorColor,
138 | @ColorInt int unselectedIndicatorColor) {
139 | mIndicatorTintColor = ColorStateList.valueOf(indicatorColor);
140 | mIndicatorTintUnselectedColor = ColorStateList.valueOf(unselectedIndicatorColor);
141 | changeIndicatorBackground();
142 | }
143 |
144 | public void changeIndicatorResource(@DrawableRes int indicatorResId) {
145 | changeIndicatorResource(indicatorResId, indicatorResId);
146 | }
147 |
148 | public void changeIndicatorResource(@DrawableRes int indicatorResId,
149 | @DrawableRes int indicatorUnselectedResId) {
150 | mIndicatorBackgroundResId = indicatorResId;
151 | mIndicatorUnselectedBackgroundResId = indicatorUnselectedResId;
152 | changeIndicatorBackground();
153 | }
154 |
155 | public interface IndicatorCreatedListener {
156 | /**
157 | * IndicatorCreatedListener
158 | *
159 | * @param view internal indicator view
160 | * @param position position
161 | */
162 | void onIndicatorCreated(View view, int position);
163 | }
164 |
165 | public void setIndicatorCreatedListener(
166 | @Nullable IndicatorCreatedListener indicatorCreatedListener) {
167 | mIndicatorCreatedListener = indicatorCreatedListener;
168 | }
169 |
170 | protected Animator createAnimatorOut(Config config) {
171 | return AnimatorInflater.loadAnimator(getContext(), config.animatorResId);
172 | }
173 |
174 | protected Animator createAnimatorIn(Config config) {
175 | Animator animatorIn;
176 | if (config.animatorReverseResId == 0) {
177 | animatorIn = AnimatorInflater.loadAnimator(getContext(), config.animatorResId);
178 | animatorIn.setInterpolator(new ReverseInterpolator());
179 | } else {
180 | animatorIn = AnimatorInflater.loadAnimator(getContext(), config.animatorReverseResId);
181 | }
182 | return animatorIn;
183 | }
184 |
185 | public void createIndicators(int count, int currentPosition) {
186 | if (mImmediateAnimatorOut.isRunning()) {
187 | mImmediateAnimatorOut.end();
188 | mImmediateAnimatorOut.cancel();
189 | }
190 |
191 | if (mImmediateAnimatorIn.isRunning()) {
192 | mImmediateAnimatorIn.end();
193 | mImmediateAnimatorIn.cancel();
194 | }
195 |
196 | // Diff View
197 | int childViewCount = getChildCount();
198 | if (count < childViewCount) {
199 | removeViews(count, childViewCount - count);
200 | } else if (count > childViewCount) {
201 | int addCount = count - childViewCount;
202 | int orientation = getOrientation();
203 | for (int i = 0; i < addCount; i++) {
204 | addIndicator(orientation);
205 | }
206 | }
207 |
208 | // Bind Style
209 | View indicator;
210 | for (int i = 0; i < count; i++) {
211 | indicator = getChildAt(i);
212 | if (currentPosition == i) {
213 | bindIndicatorBackground(indicator, mIndicatorBackgroundResId, mIndicatorTintColor);
214 | mImmediateAnimatorOut.setTarget(indicator);
215 | mImmediateAnimatorOut.start();
216 | mImmediateAnimatorOut.end();
217 | } else {
218 |
219 | bindIndicatorBackground(indicator, mIndicatorUnselectedBackgroundResId,
220 | mIndicatorTintUnselectedColor);
221 |
222 | mImmediateAnimatorIn.setTarget(indicator);
223 | mImmediateAnimatorIn.start();
224 | mImmediateAnimatorIn.end();
225 | }
226 |
227 | if (mIndicatorCreatedListener != null) {
228 | mIndicatorCreatedListener.onIndicatorCreated(indicator, i);
229 | }
230 | }
231 |
232 | mLastPosition = currentPosition;
233 | }
234 |
235 | protected void addIndicator(int orientation) {
236 | View indicator = new View(getContext());
237 | final LayoutParams params = generateDefaultLayoutParams();
238 | params.width = mIndicatorWidth;
239 | params.height = mIndicatorHeight;
240 | if (orientation == HORIZONTAL) {
241 | params.leftMargin = mIndicatorMargin;
242 | params.rightMargin = mIndicatorMargin;
243 | } else {
244 | params.topMargin = mIndicatorMargin;
245 | params.bottomMargin = mIndicatorMargin;
246 | }
247 | addView(indicator, params);
248 | }
249 |
250 | public void animatePageSelected(int position) {
251 |
252 | if (mLastPosition == position) {
253 | return;
254 | }
255 |
256 | if (mAnimatorIn.isRunning()) {
257 | mAnimatorIn.end();
258 | mAnimatorIn.cancel();
259 | }
260 |
261 | if (mAnimatorOut.isRunning()) {
262 | mAnimatorOut.end();
263 | mAnimatorOut.cancel();
264 | }
265 |
266 | View currentIndicator;
267 | if (mLastPosition >= 0 && (currentIndicator = getChildAt(mLastPosition)) != null) {
268 | bindIndicatorBackground(currentIndicator, mIndicatorUnselectedBackgroundResId,
269 | mIndicatorTintUnselectedColor);
270 | mAnimatorIn.setTarget(currentIndicator);
271 | mAnimatorIn.start();
272 | }
273 |
274 | View selectedIndicator = getChildAt(position);
275 | if (selectedIndicator != null) {
276 | bindIndicatorBackground(selectedIndicator, mIndicatorBackgroundResId,
277 | mIndicatorTintColor);
278 |
279 | mAnimatorOut.setTarget(selectedIndicator);
280 | mAnimatorOut.start();
281 | }
282 | mLastPosition = position;
283 | }
284 |
285 | protected void changeIndicatorBackground() {
286 | int count = getChildCount();
287 | if (count <= 0) {
288 | return;
289 | }
290 | View currentIndicator;
291 | for (int i = 0; i < count; i++) {
292 | currentIndicator = getChildAt(i);
293 | if (i == mLastPosition) {
294 | bindIndicatorBackground(currentIndicator, mIndicatorBackgroundResId,
295 | mIndicatorTintColor);
296 | } else {
297 | bindIndicatorBackground(currentIndicator, mIndicatorUnselectedBackgroundResId,
298 | mIndicatorTintUnselectedColor);
299 | }
300 | }
301 | }
302 |
303 | private void bindIndicatorBackground(View view, @DrawableRes int drawableRes,
304 | @Nullable ColorStateList tintColor) {
305 | if (tintColor != null) {
306 | Drawable indicatorDrawable = DrawableCompat.wrap(
307 | ContextCompat.getDrawable(getContext(), drawableRes).mutate());
308 | DrawableCompat.setTintList(indicatorDrawable, tintColor);
309 | ViewCompat.setBackground(view, indicatorDrawable);
310 | } else {
311 | view.setBackgroundResource(drawableRes);
312 | }
313 | }
314 |
315 | protected static class ReverseInterpolator implements Interpolator {
316 | @Override public float getInterpolation(float value) {
317 | return Math.abs(1.0f - value);
318 | }
319 | }
320 | }
321 |
--------------------------------------------------------------------------------