Repository: cymcsg/UltimateRecyclerView
Branch: master
Commit: 7c4a0c7fb22f
Files: 269
Total size: 979.2 KB
Directory structure:
gitextract_br_37l1j/
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── UltimateRecyclerView/
│ ├── app/
│ │ ├── build.gradle
│ │ ├── proguard-rules.pro
│ │ └── src/
│ │ ├── androidTest/
│ │ │ └── java/
│ │ │ └── com/
│ │ │ └── marshalchen/
│ │ │ └── ultimaterecyclerview/
│ │ │ └── demo/
│ │ │ └── ApplicationTest.java
│ │ └── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── marshalchen/
│ │ │ └── ultimaterecyclerview/
│ │ │ └── demo/
│ │ │ ├── LauncherActivity.java
│ │ │ ├── MainList.java
│ │ │ ├── SimpleAdapter.java
│ │ │ ├── admobdemo/
│ │ │ │ ├── SingleItemCommonLayout.java
│ │ │ │ ├── SingleItemHolder.java
│ │ │ │ ├── TestAdMobClassicActivity.java
│ │ │ │ ├── TestAdvancedAdmobActivity.java
│ │ │ │ └── ZeroStickyAdvertistmentAdapter.java
│ │ │ ├── dragdemo/
│ │ │ │ ├── DragActivity.java
│ │ │ │ └── DragAdatper.java
│ │ │ ├── expandemo/
│ │ │ │ ├── Category.java
│ │ │ │ ├── ExpCustomAdapter.java
│ │ │ │ ├── SubCategory.java
│ │ │ │ └── TestExpandableRV.java
│ │ │ ├── griddemo/
│ │ │ │ ├── GridJRAdapter.java
│ │ │ │ ├── GridLayoutRVTest.java
│ │ │ │ ├── GridStringAdapter.java
│ │ │ │ └── GridTestOnlyOnePage.java
│ │ │ ├── loadmoredemo/
│ │ │ │ ├── BasicFunctions.java
│ │ │ │ ├── DebugLoadMoreActivity.java
│ │ │ │ ├── DebugNoHeaderLoadMoreActivity.java
│ │ │ │ ├── FinalEmptyViewDisplayActivity.java
│ │ │ │ ├── FirstPageCancelLoadMore.java
│ │ │ │ ├── LineNodeActivity.java
│ │ │ │ ├── PullToRefreshActivity.java
│ │ │ │ ├── Route.java
│ │ │ │ ├── SliderHeader.java
│ │ │ │ ├── StaggerLoadMoreActivity.java
│ │ │ │ └── SwipeListViewExampleActivity.java
│ │ │ ├── modules/
│ │ │ │ ├── AbstractDataProvider.java
│ │ │ │ ├── CircularImageView.java
│ │ │ │ ├── FastBinding.java
│ │ │ │ ├── JRitem.java
│ │ │ │ ├── MainWatcher.java
│ │ │ │ ├── SampleDataboxset.java
│ │ │ │ ├── TimeLineModel.java
│ │ │ │ └── ViewPagerAdapter.java
│ │ │ ├── multiitemdemo/
│ │ │ │ ├── MultiViewTypesActivity.java
│ │ │ │ ├── MultiViewTypesRecyclerViewAdapter.java
│ │ │ │ ├── Sample1Binder.java
│ │ │ │ └── Sample2Binder.java
│ │ │ ├── rvComponents/
│ │ │ │ ├── SimpleAnimationAdapter.java
│ │ │ │ ├── SwipeAdapter.java
│ │ │ │ ├── TimeLineAdapter.java
│ │ │ │ ├── itemCommonBinder.java
│ │ │ │ ├── itemGridCellBinder.java
│ │ │ │ ├── itemNode.java
│ │ │ │ ├── itemStaggerCommonBinder.java
│ │ │ │ ├── sectionCommonAdapter.java
│ │ │ │ ├── sectionZeroAdapter.java
│ │ │ │ └── staggerAdapter.java
│ │ │ ├── scrollableobservable/
│ │ │ │ ├── BaseActivity.java
│ │ │ │ ├── BaseFragment.java
│ │ │ │ ├── ScrollObservablesActivity.java
│ │ │ │ ├── ViewPagerFragmentListSingle.java
│ │ │ │ ├── ViewPagerTabFragmentParentFragment.java
│ │ │ │ └── widget/
│ │ │ │ ├── SlidingTabLayout.java
│ │ │ │ └── SlidingTabStrip.java
│ │ │ └── swiplistdemo/
│ │ │ └── PackageAdapter.java
│ │ └── res/
│ │ ├── drawable/
│ │ │ ├── ic_add_24dp.xml
│ │ │ ├── ic_autorenew_24dp.xml
│ │ │ ├── ic_blur_linear_24dp.xml
│ │ │ ├── ic_bug_report_24dp.xml
│ │ │ ├── ic_exposure_plus_1_24dp.xml
│ │ │ ├── ic_extension_24dp.xml
│ │ │ ├── ic_remove_24dp.xml
│ │ │ └── toptint.xml
│ │ ├── drawable-mdpi/
│ │ │ └── custom_drag_frame.xml
│ │ ├── drawable-xxhdpi/
│ │ │ └── item_selector.xml
│ │ ├── layout/
│ │ │ ├── activity_drag.xml
│ │ │ ├── activity_launcher.xml
│ │ │ ├── activity_loadmore.xml
│ │ │ ├── activity_main.xml
│ │ │ ├── countable_rv_adp.xml
│ │ │ ├── custom_bottom_progressbar.xml
│ │ │ ├── custom_refresh_activity.xml
│ │ │ ├── empty_view.xml
│ │ │ ├── empty_view_v2.xml
│ │ │ ├── exp_child.xml
│ │ │ ├── exp_parent.xml
│ │ │ ├── floating_view.xml
│ │ │ ├── floatingbutton_grid_layout.xml
│ │ │ ├── grid_item.xml
│ │ │ ├── header_love.xml
│ │ │ ├── item_node.xml
│ │ │ ├── item_swipeable.xml
│ │ │ ├── list_item.xml
│ │ │ ├── list_item_header.xml
│ │ │ ├── listurv.xml
│ │ │ ├── package_row.xml
│ │ │ ├── parallax_recyclerview_header.xml
│ │ │ ├── recycler_view_adapter.xml
│ │ │ ├── rv_item_linear.xml
│ │ │ ├── rv_item_stagger.xml
│ │ │ ├── rv_sample_1.xml
│ │ │ ├── rv_sample_2.xml
│ │ │ ├── simple_scroll_activity.xml
│ │ │ ├── simplefragment_viewpager_tabhost.xml
│ │ │ ├── simplefragment_viewpaper_fragment_parent.xml
│ │ │ ├── stick_header_item.xml
│ │ │ ├── swipe_list_view_activity.xml
│ │ │ ├── tab_indicator.xml
│ │ │ └── toolbar_loadmore.xml
│ │ ├── menu/
│ │ │ ├── admenu.xml
│ │ │ └── menu_main.xml
│ │ ├── values/
│ │ │ ├── CirclarImageViewCustomStyle.xml
│ │ │ ├── arrays.xml
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── ids.xml
│ │ │ ├── scollables.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ └── values-w820dp/
│ │ └── dimens.xml
│ ├── build.gradle
│ ├── gradle/
│ │ └── wrapper/
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
│ ├── gradle.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle
│ └── ultimaterecyclerview/
│ ├── android-release-aar.gradle
│ ├── bintray-release-aar.gradle
│ ├── bintray_3_4.gradle
│ ├── build.gradle
│ ├── gradle.properties
│ ├── maven-push.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── marshalchen/
│ │ └── ultimaterecyclerview/
│ │ └── ApplicationTest.java
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── com/
│ │ └── marshalchen/
│ │ └── ultimaterecyclerview/
│ │ ├── CustomUltimateRecyclerview.java
│ │ ├── DragDropTouchListener.java
│ │ ├── ItemTouchListenerAdapter.java
│ │ ├── NormalUltimateViewAdapter.java
│ │ ├── ObservableScrollState.java
│ │ ├── ObservableScrollViewCallbacks.java
│ │ ├── RecyclerItemClickListener.java
│ │ ├── Scrollable.java
│ │ ├── SwipeDismissTouchListener.java
│ │ ├── SwipeableUltimateRecyclerview.java
│ │ ├── SwipeableUltimateViewAdapter.java
│ │ ├── URLogs.java
│ │ ├── UltimateDifferentViewTypeAdapter.java
│ │ ├── UltimateGridLayoutAdapter.java
│ │ ├── UltimateRecyclerView.java
│ │ ├── UltimateRecyclerviewViewHolder.java
│ │ ├── UltimateViewAdapter.java
│ │ ├── appPaginator/
│ │ │ ├── PageControlConst.java
│ │ │ ├── catelogGrid.java
│ │ │ ├── catelogLinear.java
│ │ │ ├── paginator.java
│ │ │ └── v4/
│ │ │ ├── catelogGrid.java
│ │ │ ├── catelogLinear.java
│ │ │ └── paginator.java
│ │ ├── dragsortadapter/
│ │ │ ├── DragInfo.java
│ │ │ ├── DragManager.java
│ │ │ ├── DragSortAdapter.java
│ │ │ ├── DragSortShadowBuilder.java
│ │ │ └── NoForegroundShadowBuilder.java
│ │ ├── expanx/
│ │ │ ├── ExpandableItemData.java
│ │ │ ├── LinearExpanxURVAdapter.java
│ │ │ ├── SmartItem.java
│ │ │ ├── Util/
│ │ │ │ ├── BaseViewHolder.java
│ │ │ │ ├── ChildClickListener.java
│ │ │ │ ├── ChildVH.java
│ │ │ │ ├── DataUtil.java
│ │ │ │ ├── ItemDataClickListener.java
│ │ │ │ ├── OnScrollToListener.java
│ │ │ │ ├── ParentVH.java
│ │ │ │ ├── child.java
│ │ │ │ ├── easyTemplateChild.java
│ │ │ │ ├── easyTemplateParent.java
│ │ │ │ └── parent.java
│ │ │ └── customizedAdapter.java
│ │ ├── grid/
│ │ │ ├── BasicGridLayoutManager.java
│ │ │ ├── GridPaddingDecorator.java
│ │ │ ├── GridSpacingItemDecoration.java
│ │ │ └── customSectionGridAdapter.java
│ │ ├── gridSection/
│ │ │ ├── HeaderViewHolder.java
│ │ │ ├── SectionedRecyclerViewAdapter.java
│ │ │ ├── SectionedSpanSizeLookup.java
│ │ │ └── SimpleSectionedAdapter.java
│ │ ├── itemTouchHelper/
│ │ │ ├── ItemTouchHelperAdapter.java
│ │ │ ├── ItemTouchHelperViewHolder.java
│ │ │ └── SimpleItemTouchHelperCallback.java
│ │ ├── layoutmanagers/
│ │ │ ├── ClassicSpanGridLayoutManager.java
│ │ │ ├── CustomLinearLayoutManager.java
│ │ │ └── ScrollSmoothLineaerLayoutManager.java
│ │ ├── multiViewTypes/
│ │ │ └── DataBinder.java
│ │ ├── quickAdapter/
│ │ │ ├── AdItemHolder.java
│ │ │ ├── AdmobAdapter.java
│ │ │ ├── BiAdAdapterSwitcher.java
│ │ │ ├── StaggerHolder.java
│ │ │ ├── easyRegularAdapter.java
│ │ │ ├── extBaseAdapter/
│ │ │ │ ├── BaseAdapterHelper.java
│ │ │ │ ├── BaseQuickAdapter.java
│ │ │ │ ├── EnhancedQuickAdapter.java
│ │ │ │ └── QuickAdapter.java
│ │ │ └── extUtimateRVA/
│ │ │ └── MultiItemTypeSupport.java
│ │ ├── stickyheadersrecyclerview/
│ │ │ ├── HeaderPositionCalculator.java
│ │ │ ├── StickyRecyclerHeadersAdapter.java
│ │ │ ├── StickyRecyclerHeadersDecoration.java
│ │ │ ├── StickyRecyclerHeadersTouchListener.java
│ │ │ ├── caching/
│ │ │ │ ├── HeaderProvider.java
│ │ │ │ └── HeaderViewCache.java
│ │ │ ├── calculation/
│ │ │ │ └── DimensionCalculator.java
│ │ │ ├── rendering/
│ │ │ │ └── HeaderRenderer.java
│ │ │ └── util/
│ │ │ ├── LinearLayoutOrientationProvider.java
│ │ │ └── OrientationProvider.java
│ │ ├── swipe/
│ │ │ ├── SimpleSwipeListener.java
│ │ │ ├── SwipeItemManagerImpl.java
│ │ │ ├── SwipeItemManagerInterface.java
│ │ │ └── SwipeLayout.java
│ │ ├── swipelistview/
│ │ │ ├── BaseSwipeListViewListener.java
│ │ │ ├── SwipeListView.java
│ │ │ ├── SwipeListViewListener.java
│ │ │ └── SwipeListViewTouchListener.java
│ │ ├── ui/
│ │ │ ├── AdGoogleDisplaySupport.java
│ │ │ ├── AnimationType.java
│ │ │ ├── CustomPtr.java
│ │ │ ├── DividerItemDecoration.java
│ │ │ ├── VerticalSwipeRefreshLayout.java
│ │ │ ├── divideritemdecoration/
│ │ │ │ ├── FlexibleDividerDecoration.java
│ │ │ │ ├── HorizontalDividerItemDecoration.java
│ │ │ │ └── VerticalDividerItemDecoration.java
│ │ │ ├── emptyview/
│ │ │ │ └── emptyViewOnShownListener.java
│ │ │ ├── floatingactionbutton/
│ │ │ │ ├── AddFloatingActionButton.java
│ │ │ │ ├── FloatingActionButton.java
│ │ │ │ ├── FloatingActionsMenu.java
│ │ │ │ └── JellyBeanFloatingActionButton.java
│ │ │ ├── header/
│ │ │ │ ├── HeaderItemDecoration.java
│ │ │ │ ├── HeaderShadowDecoration.java
│ │ │ │ └── RecyclerViewHeader.java
│ │ │ ├── swipe/
│ │ │ │ ├── SwipeableRecyclerViewTouchListener.java
│ │ │ │ └── defaultRegularSwipe.java
│ │ │ └── timelineview/
│ │ │ ├── LineType.java
│ │ │ └── TimelineView.java
│ │ └── uiUtils/
│ │ ├── CacheFragmentStatePagerAdapter.java
│ │ ├── RecyclerViewPositionHelper.java
│ │ ├── SavedStateScrolling.java
│ │ ├── ScrollUtils.java
│ │ └── TouchInterceptionLayout.java
│ └── res/
│ ├── drawable/
│ │ ├── drag_frame.xml
│ │ └── timelinedefaultmarker.xml
│ ├── drawable-v14/
│ │ └── timelinedefaultmarker.xml
│ ├── layout/
│ │ ├── bottom_progressbar.xml
│ │ ├── custom_recycler_view_layout.xml
│ │ ├── empty_progressbar.xml
│ │ ├── horizontal_recycler_view.xml
│ │ ├── slm_header.xml
│ │ ├── swipeable_ultimate_recycler_view_layout.xml
│ │ ├── ultimate_recycler_view_layout.xml
│ │ └── vertical_recycler_view.xml
│ └── values/
│ ├── attrs.xml
│ ├── color.xml
│ ├── dimens.xml
│ ├── ids.xml
│ ├── strings.xml
│ └── styles.xml
├── UpcomingChanges.md
└── _config.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Android generated
bin/
gen/
.DS_Store
# Ant
build.xml
local.properties
# Maven
target/
pom.xml.*
release.properties
# Eclipse
.classpath
.project
.externalToolBuilders/
.apt_generated/
# IntelliJ
*.iml
*.ipr
*.iws
.idea/
out/
output/
.gitignore.orig
.project.bak
.settings/org.eclipse.core.resources.prefs
.settings/org.eclipse.core.runtime.prefs
.settings/org.eclipse.jdt.apt.core.prefs
.settings/org.eclipse.jdt.core.prefs
.settings/org.eclipse.jdt.launching.prefs
.settings/
.properties
**/*.iml
**/*/.idea
**/.idea
.gradle
build/
**/.gradle
**/*/build
**/build
# key info:
ultimateandroid.jks
keystore.properties
gradleinfo.properties
# Ignore Gradle GUI config
gradle-app.setting
manifest-merger-release-report.txt
*.apk
================================================
FILE: .travis.yml
================================================
language: android
jdk:
- oraclejdk8
# Turning off caching to avoid caching Issues
# cache: false
# Using the new Container-Based Infrastructure
sudo: false
env:
global:
# Initiating clean Gradle output
- TERM=dumb
# Amount of memory granted to Gradle JVM
- GRADLE_OPTS="-Xmx512m -XX:MaxPermSize=512m"
# General Android settings used in builds
- ANDROID_TARGET=android-30
before_install:
# Making sure gradlew has executable permissions
- cd UltimateRecyclerView
- chmod a+x gradlew
- yes | sdkmanager "platforms;android-30"
android:
components:
# We are using the latest revision of Android SDK Tools
- tools
- platform-tools
- android-30
# The BuildTools version we are using for our project
- build-tools-29.0.2
# Additional components
- extra-google-google_play_services
- extra-google-m2repository
- extra-android-m2repository
licenses:
- 'android-sdk-license-.+'
script:
#./gradlew build
./gradlew assembleDebug
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# UltimateRecyclerView
[  ](https://bintray.com/marshalchen/UltimateRecyclerview/UltimateRecyclerview/_latestVersion)[](https://www.apache.org/licenses/LICENSE-2.0)[](http://waffle.io/cymcsg/UltimateRecyclerView)
#### Master branch:[](https://travis-ci.org/cymcsg/UltimateRecyclerView)
#### Dev branch:[](https://travis-ci.org/cymcsg/UltimateRecyclerView)
##### Project website:[https://github.com/cymcsg/UltimateRecyclerView](https://github.com/cymcsg/UltimateRecyclerView)
### Description
UltimateRecyclerView is a RecyclerView(advanced and flexible version of ListView) with pulling to refresh, loading more, swiping to dismiss, draging and drop, animations ,sticky header,show or hide toolbar and FAB when scrolling and many other features.You can use it ```just like RecyclerView```. Support AndroidX now.
Notice that UltimateRecyclerView is a project under development.
[Your donations is highly appreciated. Thank you!](#donations)
### Features:
* Swipe to refresh(using AndroidX SwipeRefreshLayout)
* Many kinds of animations
* Swipe to dismiss
* Parallax or normal head view
* Drag and drop items
* Loading more when reach the last item(infinite scrolling)
* Custom views in loading more
* Showing or hiding toolbar and floating button when scrolling
* Scrollbars
* Colorful styles of ``swipe to refresh``
* Sticky header like instagram
* Support different layout in adapter
* Loading adapter with animation
* Expandable view in recyclerview
#### Quick Setup (Basic Usage)
##### 1.Using Gradle:
```groovy
repositories {
mavenCentral()
google()
}
dependencies {
...
implementation 'com.marshalchen.ultimaterecyclerview:library:0.9.0'
}
```
or grab via Maven
```xml
com.marshalchen.ultimaterecyclerviewlibrary0.9.0
```
##### 2.Usage:
``` xml
```
For more details, you can read the Wiki and the demo of the project.
### Version Log
* ***v0.8.0*** Migrate to AndroidX
* ***v0.7.0*** Support most features in Recyclerview 24.0.0. Improve the UltimateAdapter. Reduce the size of the library. Fix some bugs.
* ***v0.5.8*** In this version we are now based on support library 23.4.0. We have fixed the load more and disable load more function from early triggers. There is no need to change anything from their implementations. Please read up on the example code if you have any questions from the implementations.
* ***v0.5.6*** In this version we now have 23.3.0 support library and the min version is supported all the ways to v13. New added feature that allow us to adding have node connector on each item on `linearlayoutmanager`. By extending `TimeLineView` you will now have unlimited builds from the things that connected to each dot.
* ***v0.5.0*** this library will be based on v23.2.1 from now on. if you need have the v23.1.1 please go back to the previous release. detail of this upgrade please see [#342](https://github.com/cymcsg/UltimateRecyclerView/issues/342)
* ***v0.4.9*** This is the last version that will be based on V23.1.1. and this library will not be supported on this version. For further supports please refer to the latest release.
* ***v0.3.11*** There are still version that is based on 22.+
### Upcoming features:
* Refer to discussion for headers [#299](https://github.com/cymcsg/UltimateRecyclerView/issues/299)
* Refer to discussion for the loading more [#276](https://github.com/cymcsg/UltimateRecyclerView/issues/276)
* Swipe issue and discussion [#296](https://github.com/cymcsg/UltimateRecyclerView/issues/296)
* Wishlist for [UltiamteRecyclerview 0.4.2](UpcomingChanges.md)
* and more.
> Notice that it might not be the latest version
### Demo App / Sample Code:
* Due to rapid updates and developments we have decided to host the demo APK on github
* Check out this link for [latest demonstration for the code](https://github.com/cymcsg/UltimateRecyclerView/releases)
* Video demo for [grid layout demo](https://www.youtube.com/watch?v=iTnIf-N8m1Y)
* or you can check it out already compiled at [Google Play](https://play.google.com/store/apps/details?id=com.marshalchen.ultimaterecyclerview.demo)
* You can clone the project and compile it yourself (it includes a sample), or you can check it out already compiled at Google Play
* You can read more usage in [wiki](https://github.com/cymcsg/UltimateRecyclerView/wiki) and welcome to make your own tutorials in here.
#### Welcome to fork and PR (pull request)
If you have some good ideas, please tell us. My email is cymcsg # gmail.com.And it is a good idea to put your idea on the issue. If you want to use a rapid development framework for developing apps, you can try [UltimateAndroid Framework](https://github.com/cymcsg/UltimateAndroid).
### Screenshot











### Thanks
* Use animators from [recyclerview-animators](https://github.com/wasabeef/recyclerview-animators)
* Deal with different types of LayoutManager from[SuperRecyclerView](https://github.com/Malinskiy/SuperRecyclerView)
* Divider of recyclerview[RecyclerView-FlexibleDivider](https://github.com/yqritc/RecyclerView-FlexibleDivider)
* Parallax header of the recyclerview[android-parallax-recyclerview](https://github.com/kanytu/android-parallax-recyclerview)
* Floating action button [FloatingActionButton](https://github.com/futuresimple/android-floating-action-button)
* Colorful pull to refresh [Ultra Pull To Refresh](https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh)
* Sticky section headers in RecyclerView [StickHeader](https://github.com/eowise/recyclerview-stickyheaders)
* Swipe[AndroidSwipeLayout](https://github.com/daimajia/AndroidSwipeLayout)
* Thanks [jjhesk](https://github.com/jjhesk) for doing so many work on the project
If there are someone who I do not mention here,please accept my sincerely appologies and tell me.
Donations:
Donate $9.99: [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5GYRYZVNAK2G2)
Alipay:
Bitcoin Donation Accepted

## License
```
Copyright 2014-present Marshal Chen
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
================================================
FILE: UltimateRecyclerView/app/build.gradle
================================================
apply plugin: 'com.android.application'
android {
compileSdkVersion project.ANDROID_BUILD_SDK_VERSION as int
defaultConfig {
applicationId "com.marshalchen.ultimaterecyclerview.demo"
minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
versionCode app_demo_versionCode
versionName app_demo_versionName
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
namespace 'com.marshalchen.ultimaterecyclerview.demo'
}
repositories {
flatDir {
dirs 'libs'
}
maven { url "http://dl.bintray.com/jjhesk/maven" }
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
debugImplementation "com.squareup.leakcanary:leakcanary-android:${LEAKCANARY}"
implementation 'com.google.android.gms:play-services-ads:22.6.0'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'com.hkm.loyalslider:library:1.6.2'
implementation 'jp.wasabeef:recyclerview-animators:4.0.2'
//compile 'com.marshalchen.ultimaterecyclerview:library:0.8.0'
api project(':ultimaterecyclerview')
//used in the gridlayout
// compile 'com.hkm.loyalslider:library:1.4.5' exclude group: 'android.support.v13'
}
================================================
FILE: UltimateRecyclerView/app/proguard-rules.pro
================================================
#-dontwarn com.squareup.haha.guava.**
#-dontwarn com.squareup.haha.perflib.**
#-dontwarn com.squareup.haha.trove.**
-dontwarn com.squareup.leakcanary.**
#-keep class com.squareup.haha.** { *; }
-keep class com.squareup.leakcanary.** { *; }
================================================
FILE: UltimateRecyclerView/app/src/androidTest/java/com/marshalchen/ultimaterecyclerview/demo/ApplicationTest.java
================================================
package com.marshalchen.ultimaterecyclerview.demo;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* Testing Fundamentals
*/
public class ApplicationTest extends ApplicationTestCase {
public ApplicationTest() {
super(Application.class);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/AndroidManifest.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/LauncherActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding;
import com.marshalchen.ultimaterecyclerview.itemTouchHelper.SimpleItemTouchHelperCallback;
import com.marshalchen.ultimaterecyclerview.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import java.util.ArrayList;
import java.util.List;
import jp.wasabeef.recyclerview.animators.*;
/**
* Created by Marshal Chen on 3/8/2016.
*/
public class LauncherActivity extends AppCompatActivity implements ActionMode.Callback {
UltimateRecyclerView ultimateRecyclerView;
SimpleAdapter simpleRecyclerViewAdapter = null;
LinearLayoutManager linearLayoutManager;
int moreNum = 2;
private ActionMode actionMode;
Toolbar toolbar;
boolean isDrag = true;
private ItemTouchHelper mItemTouchHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
final List stringList = new ArrayList<>();
stringList.add("111");
stringList.add("aaa");
stringList.add("222");
stringList.add("33");
stringList.add("44");
stringList.add("55");
stringList.add("66");
stringList.add("11771");
simpleRecyclerViewAdapter = new SimpleAdapter(stringList);
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(simpleRecyclerViewAdapter);
ultimateRecyclerView.addItemDecoration(headersDecor);
//// ultimateRecyclerView.setEmptyView(getResources().getIdentifier("empty_view","layout",getPackageName()));
// ultimateRecyclerView.showEmptyView();
// ultimateRecyclerView.enableLoadmore();
//simpleRecyclerViewAdapter.setCustomLoadMoreView(LayoutInflater.from(this)
// .inflate(R.layout.custom_bottom_progressbar, null));
ultimateRecyclerView.setLoadMoreView(LayoutInflater.from(this)
.inflate(R.layout.custom_bottom_progressbar, null));
ultimateRecyclerView.setParallaxHeader(getLayoutInflater().inflate(R.layout.parallax_recyclerview_header, ultimateRecyclerView.mRecyclerView, false));
// // ultimateRecyclerView.setNormalHeader(getLayoutInflater().inflate(R.layout.parallax_recyclerview_header, ultimateRecyclerView.mRecyclerView, false));
ultimateRecyclerView.setOnParallaxScroll(new UltimateRecyclerView.OnParallaxScroll() {
@Override
public void onParallaxScroll(float percentage, float offset, View parallax) {
Drawable c = toolbar.getBackground();
c.setAlpha(Math.round(127 + percentage * 128));
toolbar.setBackgroundDrawable(c);
}
});
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff"));
ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
simpleRecyclerViewAdapter.insert(moreNum++ + " Refresh things", 0);
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
// ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
// simpleRecyclerViewAdapter.notifyDataSetChanged();
}
}, 1000);
}
});
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(simpleRecyclerViewAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(ultimateRecyclerView.mRecyclerView);
simpleRecyclerViewAdapter.setOnDragStartListener(new SimpleAdapter.OnStartDragListener() {
@Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
});
ultimateRecyclerView.reenableLoadmore();
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
@Override
public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount());
simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount());
simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount());
// linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition,-1);
// linearLayoutManager.scrollToPosition(maxLastVisiblePosition);
}
}, 1000);
}
});
// ultimateRecyclerView.setDefaultSwipeToRefreshColorScheme(getResources().getColor(android.R.color.holo_blue_bright),
// getResources().getColor(android.R.color.holo_green_light),
// getResources().getColor(android.R.color.holo_orange_light),
// getResources().getColor(android.R.color.holo_red_light));
// ultimateRecyclerView.setScrollViewCallbacks(new ObservableScrollViewCallbacks() {
// @Override
// public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
//
// }
//
// @Override
// public void onDownMotionEvent() {
//
// }
//
// @Override
// public void onUpOrCancelMotionEvent(ObservableScrollState observableScrollState) {
//// if (observableScrollState == ObservableScrollState.DOWN) {
//// ultimateRecyclerView.showToolbar(toolbar, ultimateRecyclerView, getScreenHeight());
//// ultimateRecyclerView.showFloatingActionMenu();
//// } else if (observableScrollState == ObservableScrollState.UP) {
//// ultimateRecyclerView.hideToolbar(toolbar, ultimateRecyclerView, getScreenHeight());
//// ultimateRecyclerView.hideFloatingActionMenu();
//// } else if (observableScrollState == ObservableScrollState.STOP) {
//// }
// URLogs.d("onUpOrCancelMotionEvent");
// if (observableScrollState == ObservableScrollState.UP) {
// ultimateRecyclerView.hideToolbar(toolbar, ultimateRecyclerView, getScreenHeight());
// ultimateRecyclerView.hideFloatingActionMenu();
// } else if (observableScrollState == ObservableScrollState.DOWN) {
// ultimateRecyclerView.showToolbar(toolbar, ultimateRecyclerView, getScreenHeight());
// ultimateRecyclerView.showFloatingActionMenu();
// }
// }
// });
ultimateRecyclerView.showFloatingButtonView();
//
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter spinnerAdapter =
new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
for (Type type : Type.values()) {
spinnerAdapter.add(type.name());
}
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
ultimateRecyclerView.setItemAnimator(Type.values()[position].getAnimator());
ultimateRecyclerView.getItemAnimator().setAddDuration(500);
ultimateRecyclerView.getItemAnimator().setRemoveDuration(500);
}
@Override public void onNothingSelected(AdapterView> parent) {
}
});
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
simpleRecyclerViewAdapter.insert("newly added item", 1);
}
});
findViewById(R.id.del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
simpleRecyclerViewAdapter.remove(1);
}
});
//
}
private void toggleSelection(int position) {
simpleRecyclerViewAdapter.toggleSelection(position);
actionMode.setTitle("Selected " + "1");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
URLogs.d("actionmode---" + (mode == null));
mode.getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
// return false;
}
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
*
* @param mode ActionMode being prepared
* @param menu Menu used to populate action buttons
* @return true if the menu or action mode was updated, false otherwise.
*/
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// swipeToDismissTouchListener.setEnabled(false);
this.actionMode = mode;
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
this.actionMode = null;
}
//
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}
enum Type {
FadeIn(new FadeInAnimator(new OvershootInterpolator(1f))),
FadeInDown(new FadeInDownAnimator(new OvershootInterpolator(1f))),
FadeInUp(new FadeInUpAnimator(new OvershootInterpolator(1f))),
FadeInLeft(new FadeInLeftAnimator(new OvershootInterpolator(1f))),
FadeInRight(new FadeInRightAnimator(new OvershootInterpolator(1f))),
Landing(new LandingAnimator(new OvershootInterpolator(1f))),
ScaleIn(new ScaleInAnimator(new OvershootInterpolator(1f))),
ScaleInTop(new ScaleInTopAnimator(new OvershootInterpolator(1f))),
ScaleInBottom(new ScaleInBottomAnimator(new OvershootInterpolator(1f))),
ScaleInLeft(new ScaleInLeftAnimator(new OvershootInterpolator(1f))),
ScaleInRight(new ScaleInRightAnimator(new OvershootInterpolator(1f))),
FlipInTopX(new FlipInTopXAnimator(new OvershootInterpolator(1f))),
FlipInBottomX(new FlipInBottomXAnimator(new OvershootInterpolator(1f))),
FlipInLeftY(new FlipInLeftYAnimator(new OvershootInterpolator(1f))),
FlipInRightY(new FlipInRightYAnimator(new OvershootInterpolator(1f))),
SlideInLeft(new SlideInLeftAnimator(new OvershootInterpolator(1f))),
SlideInRight(new SlideInRightAnimator(new OvershootInterpolator(1f))),
SlideInDown(new SlideInDownAnimator(new OvershootInterpolator(1f))),
SlideInUp(new SlideInUpAnimator(new OvershootInterpolator(1f))),
OvershootInRight(new OvershootInRightAnimator(1.0f)),
OvershootInLeft(new OvershootInLeftAnimator(1.0f));
private BaseItemAnimator mAnimator;
Type(BaseItemAnimator animator) {
mAnimator = animator;
}
public BaseItemAnimator getAnimator() {
return mAnimator;
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/MainList.java
================================================
package com.marshalchen.ultimaterecyclerview.demo;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.marshalchen.ultimaterecyclerview.demo.admobdemo.TestAdMobClassicActivity;
import com.marshalchen.ultimaterecyclerview.demo.admobdemo.TestAdvancedAdmobActivity;
import com.marshalchen.ultimaterecyclerview.demo.expandemo.TestExpandableRV;
import com.marshalchen.ultimaterecyclerview.demo.griddemo.GridLayoutRVTest;
import com.marshalchen.ultimaterecyclerview.demo.griddemo.GridTestOnlyOnePage;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.DebugLoadMoreActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.DebugNoHeaderLoadMoreActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.FinalEmptyViewDisplayActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.FirstPageCancelLoadMore;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.LineNodeActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.PullToRefreshActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.SliderHeader;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.StaggerLoadMoreActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.SwipeListViewExampleActivity;
import com.marshalchen.ultimaterecyclerview.demo.multiitemdemo.MultiViewTypesActivity;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by hesk on 23/5/16.
*/
public class MainList extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView mList;
LinkedHashMap data = new LinkedHashMap<>();
ArrayList o = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (ListView) findViewById(android.R.id.list);
ArrayList items = new ArrayList<>();
initList();
for (Map.Entry entry : data.entrySet()) {
String key = entry.getKey();
items.add(key);
o.add(entry.getValue());
}
mList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items));
mList.setOnItemClickListener(this);
}
public void initList() {
data.put("LauncherActivity", LauncherActivity.class);
data.put("Debug Grid Test", GridLayoutRVTest.class);
data.put("Issue #374, #363 enabled and disable load more off screen", GridTestOnlyOnePage.class);
data.put("Debug load more", DebugLoadMoreActivity.class);
data.put("Debug no header", DebugNoHeaderLoadMoreActivity.class);
data.put("Debug Final Empty", FinalEmptyViewDisplayActivity.class);
data.put("Debug First Page Cancel Load More", FirstPageCancelLoadMore.class);
data.put("Debug Line Node", LineNodeActivity.class);
data.put("Debug Pull to refresh", PullToRefreshActivity.class);
data.put("Debug Admob classic", TestAdMobClassicActivity.class);
data.put("Debug Admob advanced", TestAdvancedAdmobActivity.class);
data.put("Debug Slider Header", SliderHeader.class);
data.put("Debug Stagger Load More", StaggerLoadMoreActivity.class);
data.put("Debug Swipe List", SwipeListViewExampleActivity.class);
data.put("Debug expandable", TestExpandableRV.class);
data.put("Debug multi view types", MultiViewTypesActivity.class);
}
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Intent intent = new Intent(this, o.get(position));
startActivity(intent);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/SimpleAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo;
/**
* Created by Marshal Chen on 3/8/2016.
*/
import android.graphics.Color;
import androidx.core.view.MotionEventCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import java.security.SecureRandom;
import java.util.List;
public class SimpleAdapter extends UltimateViewAdapter {
private List stringList;
public SimpleAdapter(List stringList) {
this.stringList = stringList;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (position < getItemCount() && (customHeaderView != null ? position <= stringList.size() : position < stringList.size()) && (customHeaderView != null ? position > 0 : true)) {
((ViewHolder) holder).textViewSample.setText(stringList.get(customHeaderView != null ? position - 1 : position));
// ((ViewHolder) holder).itemView.setActivated(selectedItems.get(position, false));
if (mDragStartListener != null) {
// ((ViewHolder) holder).imageViewSample.setOnTouchListener(new View.OnTouchListener() {
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
// mDragStartListener.onStartDrag(holder);
// }
// return false;
// }
// });
((ViewHolder) holder).item_view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
}
}
}
@Override
public int getAdapterItemCount() {
return stringList.size();
}
@Override
public RecyclerView.ViewHolder newFooterHolder(View view) {
// return new itemCommonBinder(view, false);
return new UltimateRecyclerviewViewHolder<>(view);
}
@Override
public RecyclerView.ViewHolder newHeaderHolder(View view) {
return new UltimateRecyclerviewViewHolder<>(view);
}
@Override
public UltimateRecyclerviewViewHolder onCreateViewHolder(ViewGroup parent) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_view_adapter, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
public void insert(String string, int position) {
insertInternal(stringList, string, position);
}
public void remove(int position) {
removeInternal(stringList, position);
}
public void clear() {
clearInternal(stringList);
}
public void swapPositions(int from, int to) {
swapPositions(stringList, from, to);
}
@Override
public long generateHeaderId(int position) {
// URLogs.d("position--" + position + " " + getItem(position));
if (getItem(position).length() > 0)
return getItem(position).charAt(0);
else return -1;
}
@Override
public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.stick_header_item, viewGroup, false);
return new RecyclerView.ViewHolder(view) {
};
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.stick_text);
textView.setText(String.valueOf(getItem(position).charAt(0)));
// viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
viewHolder.itemView.setBackgroundColor(Color.parseColor("#AAffffff"));
ImageView imageView = (ImageView) viewHolder.itemView.findViewById(R.id.stick_img);
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
imageView.setImageResource(R.drawable.jr1);
break;
case 1:
imageView.setImageResource(R.drawable.jr2);
break;
case 2:
imageView.setImageResource(R.drawable.jr3);
break;
}
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
if (fromPosition > 0 && toPosition > 0) {
swapPositions(fromPosition, toPosition);
// notifyItemMoved(fromPosition, toPosition);
super.onItemMove(fromPosition, toPosition);
}
}
@Override
public void onItemDismiss(int position) {
if (position > 0) {
remove(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();
super.onItemDismiss(position);
}
}
//
// private int getRandomColor() {
// SecureRandom rgen = new SecureRandom();
// return Color.HSVToColor(150, new float[]{
// rgen.nextInt(359), 1, 1
// });
// }
public void setOnDragStartListener(OnStartDragListener dragStartListener) {
mDragStartListener = dragStartListener;
}
class ViewHolder extends UltimateRecyclerviewViewHolder {
TextView textViewSample;
ImageView imageViewSample;
ProgressBar progressBarSample;
View item_view;
public ViewHolder(View itemView) {
super(itemView);
// itemView.setOnTouchListener(new SwipeDismissTouchListener(itemView, null, new SwipeDismissTouchListener.DismissCallbacks() {
// @Override
// public boolean canDismiss(Object token) {
// Logs.d("can dismiss");
// return true;
// }
//
// @Override
// public void onDismiss(View view, Object token) {
// // Logs.d("dismiss");
// remove(getPosition());
//
// }
// }));
textViewSample = (TextView) itemView.findViewById(
R.id.textview);
imageViewSample = (ImageView) itemView.findViewById(R.id.imageview);
progressBarSample = (ProgressBar) itemView.findViewById(R.id.progressbar);
progressBarSample.setVisibility(View.GONE);
item_view = itemView.findViewById(R.id.itemview);
}
@Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
@Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
public String getItem(int position) {
if (customHeaderView != null)
position--;
// URLogs.d("position----"+position);
if (position >= 0 && position < stringList.size())
return stringList.get(position);
else return "";
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/admobdemo/SingleItemCommonLayout.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.admobdemo;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.quickAdapter.AdItemHolder;
/**
* Created by hesk on 24/2/16.
*/
public class SingleItemCommonLayout extends AdItemHolder {
public static final int layout = R.layout.rv_item_linear;
public TextView textViewSample;
public ImageView imageViewSample;
public ProgressBar progressBarSample;
public RelativeLayout item_view;
public SingleItemCommonLayout(View itemView, int type) {
super(itemView, type);
}
@Override
protected void bindNormal(View view) {
textViewSample = (TextView) itemView.findViewById(R.id.str_textview_holder);
imageViewSample = (ImageView) itemView.findViewById(R.id.str_image_holder);
progressBarSample = (ProgressBar) itemView.findViewById(R.id.str_progress_holder);
item_view = (RelativeLayout) itemView.findViewById(R.id.str_item_view);
}
@Override
protected void bindAd(View view) {
}
@Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
@Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/admobdemo/SingleItemHolder.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.admobdemo;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.quickAdapter.AdItemHolder;
/**
* Created by hesk on 24/2/16.
*/
public class SingleItemHolder extends AdItemHolder implements
View.OnClickListener, View.OnLongClickListener {
public TextView textViewSample, num;
public ImageView imageViewSample;
public ProgressBar progressBarSample;
public SingleItemHolder(View itemView, int type) {
super(itemView, type);
}
@Override
protected void bindNormal(View view) {
textViewSample = (TextView) itemView.findViewById(R.id.textview);
num = (TextView) itemView.findViewById(R.id.numb_coun);
imageViewSample = (ImageView) itemView.findViewById(R.id.imageview);
progressBarSample = (ProgressBar) itemView.findViewById(R.id.progressbar);
progressBarSample.setVisibility(View.GONE);
}
@Override
protected void bindAd(View view) {
}
@Override
public void onClick(@NonNull View v) {
URLogs.d(textViewSample.getText() + " clicked!");
}
@Override
public boolean onLongClick(@NonNull View v) {
URLogs.d(textViewSample.getText() + " long clicked!");
return true;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/admobdemo/TestAdMobClassicActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.admobdemo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import java.util.ArrayList;
/**
* Created by hesk on 20/5/15.
*/
public class TestAdMobClassicActivity extends AppCompatActivity {
private UltimateRecyclerView ultimateRecyclerView;
private ZeroStickyAdvertistmentAdapter simpleRecyclerViewAdapter = null;
private LinearLayoutManager linearLayoutManager;
private int moreNum = 2;
private ActionMode actionMode;
private Toolbar toolbar;
private boolean isDrag = true;
private boolean admob_test_mode = false;
private AdView createadmob() {
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.MEDIUM_RECTANGLE);
mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
mAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
if (admob_test_mode)
// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
return mAdView;
}
private void enableSwipe() {
}
private void enableRefresh() {
ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.setRefreshing(false);
}
}, 1000);
}
});
}
private void enableLoadMore() {
ultimateRecyclerView.setLoadMoreView(R.layout.custom_bottom_progressbar);
ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
@Override
public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ArrayList li = new ArrayList();
li.add("No. ====" + itemsCount + "=======");
SampleDataboxset.genItems(10, li);
simpleRecyclerViewAdapter.insert(li);
}
}, 1000);
}
});
}
private void enableEmptyView() {
ultimateRecyclerView.setEmptyView(
R.layout.empty_view,
UltimateRecyclerView.EMPTY_CLEAR_ALL,
UltimateRecyclerView.STARTWITH_ONLINE_ITEMS);
}
private void enableClick() {
}
private void impleAddDrop() {
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
simpleRecyclerViewAdapter.insert(SampleDataboxset.newListFromGen(2));
}
});
findViewById(R.id.del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
simpleRecyclerViewAdapter.removeAt(3);
}
});
findViewById(R.id.toggle).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.showEmptyView();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadmore);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
/**
* wokring example 1 implementation of Admob banner with static Adview
*/
// simpleRecyclerViewAdapter = new admobdfpadapter(createadmob(), 5, stringList);
/**
* working example 2 with multiple called Adviews
*/
simpleRecyclerViewAdapter = new ZeroStickyAdvertistmentAdapter(createadmob(), SampleDataboxset.newListFromGen());
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
ultimateRecyclerView.setItemViewCacheSize(3);
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#f5f5ff"));
enableEmptyView();
enableRefresh();
enableLoadMore();
enableClick();
impleAddDrop();
}
private void toggleSelection(int position) {
simpleRecyclerViewAdapter.toggleSelection(position);
actionMode.setTitle("Selected " + "1");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/admobdemo/TestAdvancedAdmobActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.admobdemo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.marshalchen.ultimaterecyclerview.quickAdapter.AdmobAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import com.marshalchen.ultimaterecyclerview.quickAdapter.BiAdAdapterSwitcher;
import com.marshalchen.ultimaterecyclerview.ui.AdGoogleDisplaySupport;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hesk on 4/8/15.
*/
public class TestAdvancedAdmobActivity extends AppCompatActivity {
private UltimateRecyclerView ultimateRecyclerView;
private boolean admob_test_mode = false;
private LinearLayoutManager linearLayoutManager;
private Toolbar toolbar;
private BiAdAdapterSwitcher bi_sw;
public static class adap extends AdmobAdapter {
public adap(RelativeLayout v, List L) {
super(v, false, 13, L, null);
}
@Override
protected int getNormalLayoutResId() {
return getIdRV();
}
@Override
protected SingleItemHolder newViewHolder(View mview) {
return new SingleItemHolder(mview, VIEW_TYPES.NORMAL);
}
/**
* binding normal view holder
*
* @param holder holder class
* @param data data
* @param position position
*/
@Override
protected void withBindHolder(SingleItemHolder holder, String data, int position) {
bindthisInhere(holder, data, position);
}
}
public static class regular extends easyRegularAdapter {
public regular(List list) {
super(list);
}
@Override
protected int getNormalLayoutResId() {
return getIdRV();
}
@Override
protected SingleItemHolder newViewHolder(View view) {
return new SingleItemHolder(view, VIEW_TYPES.NORMAL);
}
@Override
protected void withBindHolder(SingleItemHolder holderm, String data, int position) {
bindthisInhere(holderm, data, position);
}
}
private static void bindthisInhere(SingleItemHolder d, String data, int pos) {
d.textViewSample.setText(data);
d.num.setText("@:" + pos);
}
private static int getIdRV() {
return R.layout.countable_rv_adp;
}
private RelativeLayout createadmob() {
AdSize adSize = AdSize.SMART_BANNER;
DisplayMetrics dm = getResources().getDisplayMetrics();
double density = dm.density * 160;
double x = Math.pow(dm.widthPixels / density, 2);
double y = Math.pow(dm.heightPixels / density, 2);
double screenInches = Math.sqrt(x + y);
if (screenInches > 8) { // > 728 X 90
adSize = AdSize.LEADERBOARD;
} else if (screenInches > 6) { // > 468 X 60
adSize = AdSize.MEDIUM_RECTANGLE;
} else { // > 320 X 50
adSize = AdSize.BANNER;
}
adSize = AdSize.MEDIUM_RECTANGLE;
final AdView mAdView = new AdView(this);
mAdView.setAdSize(adSize);
mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
if (admob_test_mode)
// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
DisplayMetrics displaymetrics = new DisplayMetrics();
final RelativeLayout layout = AdGoogleDisplaySupport.initialSupport(this, displaymetrics);
final double ratio = AdGoogleDisplaySupport.ratioMatching(displaymetrics);
final int ad_height = AdGoogleDisplaySupport.defaultHeight(displaymetrics);
AdGoogleDisplaySupport.panelAdjust(mAdView, (int) (ad_height * ratio));
// get display info
/* G.display_w = displayMetrics.widthPixels;
G.display_h = displayMetrics.heightPixels;
G.scale = Math.max(G.display_w/1280.0f, G.display_h/800.0f);*/
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
super.onAdLoaded();
int h = mAdView.getLayoutParams().height;
AdGoogleDisplaySupport.scale(mAdView, ratio);
AdGoogleDisplaySupport.panelAdjust(mAdView, (int) (h * ratio));
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
}
});
layout.addView(mAdView);
return layout;
}
/**
* example 1 implementation of the switch view
*/
private BiAdAdapterSwitcher imple_switch_view(final UltimateRecyclerView rv) {
final adap adp1 = new adap(createadmob(), new ArrayList());
final regular adp2 = new regular(new ArrayList());
final BiAdAdapterSwitcher switchable = new BiAdAdapterSwitcher(rv, adp2, adp1);
return switchable;
}
private Handler osh = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadmore);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff"));
/**
* example 2 implementation enhancement of list view
*/
bi_sw = imple_switch_view(ultimateRecyclerView)
.onEnableRefresh(100)
.EnableAutoDisableLoadMoreByMaxPages()
.onEnableLoadmore(R.layout.custom_bottom_progressbar, 2000, new BiAdAdapterSwitcher.onLoadMore() {
@Override
public boolean request_start(int current_page_no, int itemsCount, int maxLastVisiblePosition, final BiAdAdapterSwitcher bi, boolean refresh) {
osh.postDelayed(new Runnable() {
@Override
public void run() {
bi.load_more_data(SampleDataboxset.newList(5));
//test the max pages
bi.setMaxPages(10);
}
}, 2000);
return true;
}
});
TextView b = (TextView) findViewById(R.id.del);
b.setText("with Ad");
TextView a = (TextView) findViewById(R.id.add);
a.setText("with out Ad");
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* example 2 implementation enhancement of list view
* without advertisement configurations
*/
bi_sw.init(false);
}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* example 2 implementation enhancement of list view
* with advertisement configuration
*/
bi_sw.init(true);
}
});
setup_spinner();
}
private void remove_all_items() {
bi_sw.removeALL();
}
private void setup_spinner() {
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setPrompt("test functions");
ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
spinnerAdapter.add("noth");
spinnerAdapter.add("remove all");
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
// ultimateRecyclerView.setItemAnimator(Type.values()[position].getAnimator());
// ultimateRecyclerView.getItemAnimator().setAddDuration(300);
// ultimateRecyclerView.getItemAnimator().setRemoveDuration(300);
if (position == 1) {
remove_all_items();
spinner.setSelection(0, true);
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/admobdemo/ZeroStickyAdvertistmentAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.admobdemo;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import com.google.android.gms.ads.AdView;
import com.marshalchen.ultimaterecyclerview.quickAdapter.AdmobAdapter;
import java.util.List;
/**
* Created by hesk on 20/5/15.
*/
public class ZeroStickyAdvertistmentAdapter extends AdmobAdapter {
public ZeroStickyAdvertistmentAdapter(AdView v, List f) {
super(v, false, 12, f);
}
public ZeroStickyAdvertistmentAdapter(AdView v, int e, List f, AdviewListener listener) {
super(v, false, e, f, listener);
}
@Override
protected int getNormalLayoutResId() {
return SingleItemCommonLayout.layout;
}
@Override
protected SingleItemCommonLayout newViewHolder(View mview) {
return new SingleItemCommonLayout(mview, VIEW_TYPES.NORMAL);
}
/**
* binding normal view holder
*
* @param holder holder class
* @param data data
* @param position position
*/
@Override
protected void withBindHolder(SingleItemCommonLayout holder, String data, int position) {
holder.textViewSample.setText(data);
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
// TextView textView = (TextView) viewHolder.itemView;
// textView.setText(String.valueOf(getItem(i).charAt(0)));
// viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
}
/*
@Override
public long getHeaderId(int position) {
if (position == 0) {
return -1;
} else {
return getItem(position).charAt(0);
}
}
*/
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/dragdemo/DragActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.dragdemo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding;
import java.util.ArrayList;
import java.util.List;
public class DragActivity extends AppCompatActivity {
RecyclerView ultimateRecyclerView;
DragAdatper simpleRecyclerViewAdapter = null;
LinearLayoutManager linearLayoutManager;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (RecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
List stringList = new ArrayList<>();
stringList.add("aa");
stringList.add("bb");
stringList.add("cc");
stringList.add("dd");
List data = new ArrayList<>();
data.add(1);
data.add(2);
data.add(3);
data.add(4);
data.add(15);
simpleRecyclerViewAdapter = new DragAdatper(ultimateRecyclerView, data);
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
/*
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter spinnerAdapter =
new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
for (Type type : Type.values()) {
spinnerAdapter.add(type.name());
}
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
ultimateRecyclerView.setItemAnimator(Type.values()[position].getAnimator());
ultimateRecyclerView.getItemAnimator().setAddDuration(300);
ultimateRecyclerView.getItemAnimator().setRemoveDuration(300);
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
*/
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}
/* enum Type {
FadeIn(new FadeInAnimator()),
FadeInDown(new FadeInDownAnimator()),
FadeInUp(new FadeInUpAnimator()),
FadeInLeft(new FadeInLeftAnimator()),
FadeInRight(new FadeInRightAnimator()),
Landing(new LandingAnimator()),
ScaleIn(new ScaleInAnimator()),
ScaleInTop(new ScaleInTopAnimator()),
ScaleInBottom(new ScaleInBottomAnimator()),
ScaleInLeft(new ScaleInLeftAnimator()),
ScaleInRight(new ScaleInRightAnimator()),
FlipInTopX(new FlipInTopXAnimator()),
FlipInBottomX(new FlipInBottomXAnimator()),
FlipInLeftY(new FlipInLeftYAnimator()),
FlipInRightY(new FlipInRightYAnimator()),
SlideInLeft(new SlideInLeftAnimator()),
SlideInRight(new SlideInRightAnimator()),
SlideInDown(new SlideInDownAnimator()),
SlideInUp(new SlideInUpAnimator()),
OvershootInRight(new OvershootInRightAnimator()),
OvershootInLeft(new OvershootInLeftAnimator());
private BaseItemAnimator mAnimator;
Type(BaseItemAnimator animator) {
mAnimator = animator;
}
public BaseItemAnimator getAnimator() {
return mAnimator;
}
}
*/
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/dragdemo/DragAdatper.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.dragdemo;
import android.graphics.Point;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.dragsortadapter.DragSortAdapter;
import com.marshalchen.ultimaterecyclerview.dragsortadapter.NoForegroundShadowBuilder;
import java.util.List;
public class DragAdatper extends DragSortAdapter {
private List stringList;
public DragAdatper(RecyclerView recyclerView, List data) {
super(recyclerView);
this.stringList = data;
}
@Override public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.rv_item_linear, parent, false);
MainViewHolder holder = new MainViewHolder(this, view);
view.setOnClickListener(holder);
view.setOnLongClickListener(holder);
return holder;
}
@Override public void onBindViewHolder(final MainViewHolder holder, final int position) {
Integer itemId = stringList.get(position);
holder.textViewSample.setText(itemId + " ");
// NOTE: check for getDraggingId() match to set an "invisible space" while dragging
// holder.container.setVisibility(getDraggingId() == itemId ? View.INVISIBLE : View.VISIBLE);
// holder.container.postInvalidate();
}
@Override public long getItemId(int position) {
// URLogs.d("hashcode---"+stringList.get(position).hashCode()+" "+position);
return stringList.get(position).hashCode();
}
protected static int convertToOriginalPosition(int position, int dragInitial, int dragCurrent) {
if (dragInitial < 0 || dragCurrent < 0) {
// not dragging
return position;
} else {
if ((dragInitial == dragCurrent) ||
((position < dragInitial) && (position < dragCurrent)) ||
(position > dragInitial) && (position > dragCurrent)) {
return position;
} else if (dragCurrent < dragInitial) {
if (position == dragCurrent) {
return dragInitial;
} else {
return position - 1;
}
} else { // if (dragCurrent > dragInitial)
if (position == dragCurrent) {
return dragInitial;
} else {
return position + 1;
}
}
}
}
@Override public int getItemCount() {
return stringList.size();
}
@Override public int getPositionForId(long id) {
return stringList.indexOf((int) id);
}
@Override public boolean move(int fromPosition, int toPosition) {
stringList.add(toPosition, stringList.remove(fromPosition));
return true;
}
static class MainViewHolder extends DragSortAdapter.ViewHolder implements
View.OnClickListener, View.OnLongClickListener {
TextView textViewSample;
ImageView imageViewSample;
ProgressBar progressBarSample;
public MainViewHolder(DragSortAdapter adapter, View itemView) {
super(adapter, itemView);
textViewSample = (TextView) itemView.findViewById(
R.id.textview);
imageViewSample = (ImageView) itemView.findViewById(R.id.imageview);
progressBarSample = (ProgressBar) itemView.findViewById(R.id.progressbar);
progressBarSample.setVisibility(View.GONE);
}
@Override public void onClick(@NonNull View v) {
URLogs.d(textViewSample.getText() + " clicked!");
}
@Override public boolean onLongClick(@NonNull View v) {
startDrag();
return true;
}
@Override public View.DragShadowBuilder getShadowBuilder(View itemView, Point touchPoint) {
return new NoForegroundShadowBuilder(itemView, touchPoint);
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/expandemo/Category.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.expandemo;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.expanx.SmartItem;
import com.marshalchen.ultimaterecyclerview.expanx.Util.easyTemplateParent;
/**
* Created by hesk on 16/7/15.
*/
public class Category extends easyTemplateParent {
public Category(View itemView) {
super(itemView);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/expandemo/ExpCustomAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.expandemo;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.expanx.SmartItem;
import com.marshalchen.ultimaterecyclerview.expanx.Util.DataUtil;
import com.marshalchen.ultimaterecyclerview.expanx.customizedAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hesk on 16/7/15.
*/
public class ExpCustomAdapter extends customizedAdapter {
public ExpCustomAdapter(Context context) {
super(context);
}
public static List getPreCodeMenu(String[] a, String[] b, String[] c) {
List e = new ArrayList<>();
e.add(SmartItem.parent("hones", "open", DataUtil.getSmallList(a)));
e.add(SmartItem.parent("XXX", "open", DataUtil.getSmallList(b)));
e.add(SmartItem.parent("RIVER", "open", DataUtil.getSmallList(c)));
return e;
}
/**
* please do work on this id the custom object is true
*
* @param parentview the inflated view
* @return the actual parent holder
*/
@Override
protected Category iniCustomParentHolder(View parentview) {
return new Category(parentview);
}
/**
* please do work on this if the custom object is true
*
* @param childview the inflated view
* @return the actual child holder
*/
@Override
protected SubCategory iniCustomChildHolder(View childview) {
return new SubCategory(childview);
}
@Override
protected int getLayoutResParent() {
return R.layout.exp_parent;
}
@Override
protected int getLayoutResChild() {
return R.layout.exp_child;
}
@Override
protected List getChildrenByPath(String path, int depth, int position) {
return null;
}
@Override
public RecyclerView.ViewHolder newFooterHolder(View view) {
return new UltimateRecyclerviewViewHolder(view);
}
@Override
public RecyclerView.ViewHolder newHeaderHolder(View view) {
return new UltimateRecyclerviewViewHolder(view);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/expandemo/SubCategory.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.expandemo;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.expanx.SmartItem;
import com.marshalchen.ultimaterecyclerview.expanx.Util.easyTemplateChild;
/**
* Created by hesk on 16/7/15.
*/
public class SubCategory extends easyTemplateChild {
public SubCategory(View itemView) {
super(itemView);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/expandemo/TestExpandableRV.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.expandemo;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding;
/**
* Created by hesk on 16/7/15.
*/
public class TestExpandableRV extends AppCompatActivity {
private static String[] sampledatagroup1 = {
"peter", "http://google",
"billy", "http://google",
"lisa", "http://google",
"visa", "http://google"
};
private static String[] sampledatagroup2 = {
"mother", "http://google",
"father", "http://google",
"son", "http://google",
"holy spirit", "http://google",
"god the son", "http://google"
};
private static String[] sampledatagroup3 = {
"SONY", "http://google",
"LG", "http://google",
"SAMSUNG", "http://google",
"XIAOMI", "http://google",
"HTC", "http://google"
};
private UltimateRecyclerView ultimateRecyclerView;
private ExpCustomAdapter simpleRecyclerViewAdapter = null;
private LinearLayoutManager linearLayoutManager;
private int moreNum = 2;
private ActionMode actionMode;
private Toolbar toolbar;
boolean isDrag = true;
private boolean admob_test_mode = false;
private void enableSwipe() {
}
private void addExpandableFeatures() {
ultimateRecyclerView.getItemAnimator().setAddDuration(100);
ultimateRecyclerView.getItemAnimator().setRemoveDuration(100);
ultimateRecyclerView.getItemAnimator().setMoveDuration(200);
ultimateRecyclerView.getItemAnimator().setChangeDuration(100);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadmore);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
/**
* this is the adapter for the expanx
*/
simpleRecyclerViewAdapter = new ExpCustomAdapter(this);
simpleRecyclerViewAdapter.addAll(ExpCustomAdapter.getPreCodeMenu(sampledatagroup1, sampledatagroup2, sampledatagroup3), 0);
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff"));
addExpandableFeatures();
}
private void toggleSelection(int position) {
simpleRecyclerViewAdapter.toggleSelection(position);
actionMode.setTitle("Selected " + "1");
}
public int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
//
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/griddemo/GridJRAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.griddemo;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.UltimateGridLayoutAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.JRitem;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.itemGridCellBinder;
import java.util.List;
/**
* Created by hesk on 3/2/16.
*/
public class GridJRAdapter extends UltimateGridLayoutAdapter {
public GridJRAdapter(List hand) {
super(hand);
}
/**
* the layout id for the normal data
*
* @return the ID
*/
@Override
protected int getNormalLayoutResId() {
return itemGridCellBinder.layout;
}
/**
* this is the Normal View Holder initiation
*
* @param view view
* @return holder
*/
@Override
protected itemGridCellBinder newViewHolder(View view) {
return new itemGridCellBinder(view, true);
}
@Override
public long generateHeaderId(int position) {
return 0;
}
/**
* binding normal view holder
*
* @param holder holder class
* @param data data
* @param position position
*/
@Override
protected void withBindHolder(itemGridCellBinder holder, JRitem data, int position) {
}
@Override
protected void bindNormal(itemGridCellBinder b, JRitem jRitem, int position) {
b.textViewSample.setText(jRitem.train_name);
b.imageViewSample.setImageResource(jRitem.photo_id);
}
@Override
public UltimateRecyclerviewViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
return new UltimateRecyclerviewViewHolder(parent);
}
@Override
public itemGridCellBinder newFooterHolder(View view) {
return new itemGridCellBinder(view, false);
}
@Override
public itemGridCellBinder newHeaderHolder(View view) {
return new itemGridCellBinder(view, false);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/griddemo/GridLayoutRVTest.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.griddemo;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.LayoutRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.util.DisplayMetrics;
import android.view.ActionMode;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.JRitem;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.grid.BasicGridLayoutManager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hesk on 24/8/15.
*/
public class GridLayoutRVTest extends AppCompatActivity {
protected UltimateRecyclerView listuv;
protected GridJRAdapter mGridAdapter = null;
private BasicGridLayoutManager mGridLayoutManager;
private int moreNum = 2, columns = 2;
private ActionMode actionMode;
private Toolbar mToolbar;
boolean isDrag = true;
private ItemTouchHelper mItemTouchHelper;
public static final String TAG = "GLV";
@LayoutRes
protected int getMainLayout() {
return R.layout.floatingbutton_grid_layout;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getMainLayout());
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
listuv = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
mGridAdapter = new GridJRAdapter(getJRList());
mGridAdapter.setSpanColumns(columns);
mGridLayoutManager = new BasicGridLayoutManager(this, columns, mGridAdapter);
listuv.setLayoutManager(mGridLayoutManager);
listuv.setHasFixedSize(true);
listuv.setSaveEnabled(true);
listuv.setClipToPadding(false);
// mGridAdapter.setCustomLoadMoreView(LayoutInflater.from(this).inflate(R.layout.custom_bottom_progressbar, null));
listuv.setNormalHeader(setupHeaderView());
final Handler f = new Handler();
listuv.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
@Override
public void loadMore(int itemsCount, int maxLastVisiblePosition) {
// Log.d(TAG, itemsCount + " :: " + itemsCount);
f.postDelayed(new Runnable() {
@Override
public void run() {
mGridAdapter.insert(SampleDataboxset.genJRList(5));
afterAdd();
}
}, 2000);
}
});
// listuv.enableLoadmore();
// listuv.disableLoadmore();
listuv.setLoadMoreView(R.layout.custom_bottom_progressbar);
listuv.setAdapter(mGridAdapter);
listuv.setItemAnimator(new DefaultItemAnimator());
harness_control();
}
protected void afterAdd() {
}
private List getJRList() {
List team = new ArrayList<>();
//you can make your own test for starting-zero-data
// team = SampleDataboxset.genJRList(2);
return team;
}
private void dimension_columns() {
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpWidth = outMetrics.widthPixels / density;
columns = Math.round(dpWidth / 300);
}
private View setupHeaderView() {
View custom_header = LayoutInflater.from(this).inflate(R.layout.header_love, null, false);
return custom_header;
}
private void harness_control() {
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mGridAdapter.insert(SampleDataboxset.genJRList(4));
}
});
findViewById(R.id.del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mGridAdapter.removeLast();
}
});
findViewById(R.id.delall).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mGridAdapter.removeAll();
}
});
findViewById(R.id.add_one).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mGridAdapter.insertFirst(SampleDataboxset.genJRSingle());
}
});
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listuv.reenableLoadmore();
}
});
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/griddemo/GridStringAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.griddemo;
import androidx.recyclerview.widget.GridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.UltimateGridLayoutAdapter;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.itemGridCellBinder;
import java.util.List;
/**
* Created by hesk on 24/8/15.
*/
public class GridStringAdapter extends UltimateGridLayoutAdapter {
public GridStringAdapter(List hand) {
super(hand);
}
/**
* the layout id for the normal data
*
* @return the ID
*/
@Override
protected int getNormalLayoutResId() {
return R.layout.grid_item;
}
/**
* this is the Normal View Holder initiation
*
* @param view view
* @return holder
*/
@Override
protected itemGridCellBinder newViewHolder(View view) {
return new itemGridCellBinder(view, true);
}
@Override
public itemGridCellBinder newFooterHolder(View view) {
return new itemGridCellBinder(view, false);
}
@Override
public itemGridCellBinder newHeaderHolder(View view) {
return new itemGridCellBinder(view, false);
}
@Override
public long generateHeaderId(int position) {
return 0;
}
/**
* binding normal view holder
*
* @param holder holder class
* @param data data
* @param position position
*/
@Override
protected void withBindHolder(itemGridCellBinder holder, String data, int position) {
}
@Override
public UltimateRecyclerviewViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
return new UltimateRecyclerviewViewHolder(parent);
}
@Override
protected void bindNormal(itemGridCellBinder b, String s, int position) {
b.textViewSample.setText(s);
b.imageViewSample.setImageResource(SampleDataboxset.getGirlImageRandom());
}
//https://gist.github.com/yqritc/ccca77dc42f2364777e1
public static class GridSpan extends GridLayoutManager.SpanSizeLookup {
final private int columns;
final private int intervalRow;
final private GridStringAdapter mGridAdapter;
public GridSpan(int col, int intervalRow, GridStringAdapter mGridAdapter) {
this.columns = col;
this.intervalRow = intervalRow;
this.mGridAdapter = mGridAdapter;
}
/**
* Returns the number of span occupied by the item at position.
*
* @param position The adapter position of the item
* @return The number of spans occupied by the item at the provided position
*/
@Override
public int getSpanSize(int position) {
if (position == mGridAdapter.getAdapterItemCount()) {
return columns;
} else {
int mIntervalHeader = columns * intervalRow;
int h = position % mIntervalHeader == 0 ? columns : 1;
return h;
}
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/griddemo/GridTestOnlyOnePage.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.griddemo;
import android.os.Bundle;
import android.os.Handler;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
/**
* This is the fix the off screen detection issue
* Created by hesk on 23/5/16.
*/
public class GridTestOnlyOnePage extends GridLayoutRVTest {
Handler poster = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
poster.postDelayed(new Runnable() {
@Override
public void run() {
listuv.reenableLoadmore();
mGridAdapter.insert(SampleDataboxset.genJRList(5));
}
}, 1000);
}
@Override
protected void afterAdd() {
listuv.disableLoadmore();
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/BasicFunctions.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.ActionMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.marshalchen.ultimaterecyclerview.DragDropTouchListener;
import com.marshalchen.ultimaterecyclerview.ItemTouchListenerAdapter;
import com.marshalchen.ultimaterecyclerview.ObservableScrollState;
import com.marshalchen.ultimaterecyclerview.ObservableScrollViewCallbacks;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.layoutmanagers.ClassicSpanGridLayoutManager;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import com.marshalchen.ultimaterecyclerview.ui.AnimationType;
import com.marshalchen.ultimaterecyclerview.layoutmanagers.ScrollSmoothLineaerLayoutManager;
/**
* Created by hesk on 19/2/16.
*/
public abstract class BasicFunctions extends AppCompatActivity {
protected UltimateRecyclerView ultimateRecyclerView;
protected void enableParallaxHeader() {
ultimateRecyclerView.setParallaxHeader(getLayoutInflater().inflate(R.layout.parallax_recyclerview_header, ultimateRecyclerView.mRecyclerView, false));
ultimateRecyclerView.setOnParallaxScroll(new UltimateRecyclerView.OnParallaxScroll() {
@Override
public void onParallaxScroll(float percentage, float offset, View parallax) {
Drawable c = toolbar.getBackground();
c.setAlpha(Math.round(127 + percentage * 128));
toolbar.setBackgroundDrawable(c);
}
});
}
protected void enableLoadMore() {
// StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(simpleRecyclerViewAdapter);
// ultimateRecyclerView.addItemDecoration(headersDecor);
ultimateRecyclerView.setLoadMoreView(R.layout.custom_bottom_progressbar);
ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
@Override
public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
status_progress = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
onLoadmore();
status_progress = false;
}
}, 500);
}
});
}
protected abstract void onLoadmore();
protected abstract void onFireRefresh();
protected void enableRefresh() {
// ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
// @Override
// public void onRefresh() {
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// onFireRefresh();
// }
// }, 1000);
// }
// });
// ultimateRecyclerView.setDefaultSwipeToRefreshColorScheme(getResources().getColor(android.R.color.holo_blue_bright),
// getResources().getColor(android.R.color.holo_green_light),
// getResources().getColor(android.R.color.holo_orange_light),
// getResources().getColor(android.R.color.holo_red_light));
}
protected final void configStaggerLayoutManager(UltimateRecyclerView rv, easyRegularAdapter ad) {
StaggeredGridLayoutManager gaggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
rv.setLayoutManager(gaggeredGridLayoutManager);
}
protected final void configGridLayoutManager(UltimateRecyclerView rv, easyRegularAdapter ad) {
final ClassicSpanGridLayoutManager mgm = new ClassicSpanGridLayoutManager(this, 2, ad);
rv.setLayoutManager(mgm);
}
protected final void configLinearLayoutManager(UltimateRecyclerView rv) {
final ScrollSmoothLineaerLayoutManager mgm = new ScrollSmoothLineaerLayoutManager(this, LinearLayoutManager.VERTICAL, false, 300);
rv.setLayoutManager(mgm);
}
protected final void enableScrollControl() {
ultimateRecyclerView.setScrollViewCallbacks(new ObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
URLogs.d("onScrollChanged: " + dragging);
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ObservableScrollState observableScrollState) {
URLogs.d("onUpOrCancelMotionEvent");
if (observableScrollState == ObservableScrollState.UP) {
ultimateRecyclerView.hideToolbar(toolbar, ultimateRecyclerView, getScreenHeight());
ultimateRecyclerView.hideFloatingActionMenu();
} else if (observableScrollState == ObservableScrollState.DOWN) {
ultimateRecyclerView.showToolbar(toolbar, ultimateRecyclerView, getScreenHeight());
ultimateRecyclerView.showFloatingActionMenu();
}
}
});
ultimateRecyclerView.showFloatingButtonView();
}
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_SHOW_LOADMORE_ONLY);
ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_CLEAR_ALL);
}
protected void enableSwipe() {
}
protected void enableItemClick() {
ItemTouchListenerAdapter itemTouchListenerAdapter = new ItemTouchListenerAdapter(ultimateRecyclerView.mRecyclerView,
new ItemTouchListenerAdapter.RecyclerViewOnItemClickListener() {
@Override
public void onItemClick(RecyclerView parent, View clickedView, int position) {
}
@Override
public void onItemLongClick(RecyclerView parent, View clickedView, int position) {
URLogs.d("onItemLongClick()" + isDrag);
if (isDrag) {
URLogs.d("onItemLongClick()" + isDrag);
// dragDropTouchListener.startDrag();
// ultimateRecyclerView.enableDefaultSwipeRefresh(false);
}
}
});
ultimateRecyclerView.mRecyclerView.addOnItemTouchListener(itemTouchListenerAdapter);
}
protected abstract void addButtonTrigger();
protected abstract void removeButtonTrigger();
protected void setupSpinnerSelection(Spinner sp, ArrayAdapter adapter) {
adapter.add("- select -");
/**
* a list of selection for other tests
*/
for (Route type : Route.values()) {
adapter.add(type.getNameDisplay());
}
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
if (position > 0) {
Route.values()[position - 1].start(getApplication());
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
}
protected void setupSpinnerAnimationSelection(Spinner spinner, ArrayAdapter adapter) {
adapter.add("- animator -");
for (AnimationType type : AnimationType.values()) {
adapter.add(type.name());
}
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
if (position > 0) {
ultimateRecyclerView.setItemAnimator(AnimationType.values()[position - 1].getAnimator());
ultimateRecyclerView.getItemAnimator().setAddDuration(300);
ultimateRecyclerView.getItemAnimator().setRemoveDuration(300);
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
}
private void bButtons() {
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addButtonTrigger();
}
});
findViewById(R.id.del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
removeButtonTrigger();
}
});
findViewById(R.id.toggle).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toggleButtonTrigger();
}
});
}
protected void toggleButtonTrigger() {
if (!status_progress) {
isEnableAutoLoadMore = !isEnableAutoLoadMore;
if (isEnableAutoLoadMore) {
ultimateRecyclerView.reenableLoadmore();
}
}
}
protected ActionMode actionMode;
protected Toolbar toolbar;
protected LinearLayoutManager linearLayoutManager;
private int moreNum = 2;
protected boolean isDrag = true, isEnableAutoLoadMore = true, status_progress = false;
private DragDropTouchListener dragDropTouchListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadmore);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
doURV(ultimateRecyclerView);
bButtons();
ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
setupSpinnerSelection((Spinner) findViewById(R.id.spinner), spinnerAdapter);
}
public int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
protected abstract void doURV(UltimateRecyclerView urv);
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/DebugLoadMoreActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import com.marshalchen.ultimaterecyclerview.ui.swipe.SwipeableRecyclerViewTouchListener;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.ui.swipe.defaultRegularSwipe;
import java.util.ArrayList;
/**
* Created by hesk on 7/1/2015.
*/
public class DebugLoadMoreActivity extends BasicFunctions {
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
@Override
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_SHOW_LOADMORE_ONLY);
}
@Override
protected void onLoadmore() {
// SampleDataboxset.insertMore(simpleRecyclerViewAdapter, 2);
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 2);
// linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
// linearLayoutManager.scrollToPosition(maxLastVisiblePosition);
/**
* this is the example for making the function test for loading more and disable loading more
*/
/* if (isEnableAutoLoadMore) {
ultimateRecyclerView.enableLoadmore();
} else {
ultimateRecyclerView.disableLoadmore();
}*/
}
@Override
protected void enableSwipe() {
super.enableSwipe();
ultimateRecyclerView.addOnItemTouchListener(new SwipeableRecyclerViewTouchListener(ultimateRecyclerView.mRecyclerView, new defaultRegularSwipe<>(simpleRecyclerViewAdapter)));
}
@Override
protected void addButtonTrigger() {
simpleRecyclerViewAdapter.insertFirst("rand added item");
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeLast();
}
@Override
protected void onFireRefresh() {
// simpleRecyclerViewAdapter.insertLast(moreNum++ + " Refresh things");
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
//ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
//simpleRecyclerViewAdapter.notifyDataSetChanged();
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.disableLoadmore();
//ultimateRecyclerView.showEmptyView();
}
@Override
protected void doURV(UltimateRecyclerView ultimateRecyclerView) {
ultimateRecyclerView.setHasFixedSize(false);
simpleRecyclerViewAdapter = new sectionZeroAdapter(new ArrayList());
configLinearLayoutManager(ultimateRecyclerView);
enableParallaxHeader();
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffff66ff"));
enableRefresh();
// enableScrollControl();
// enableSwipe();
// enableItemClick();
//ultimateRecyclerView.setItemViewCacheSize(simpleRecyclerViewAdapter.getAdditionalItems());
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
private void toggleSelection(int position) {
simpleRecyclerViewAdapter.toggleSelection(position);
actionMode.setTitle("Selected " + "1");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
//
/* @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}*/
/* enum Type {
FadeIn(new FadeInAnimator()),
FadeInDown(new FadeInDownAnimator()),
FadeInUp(new FadeInUpAnimator()),
FadeInLeft(new FadeInLeftAnimator()),
FadeInRight(new FadeInRightAnimator()),
Landing(new LandingAnimator()),
ScaleIn(new ScaleInAnimator()),
ScaleInTop(new ScaleInTopAnimator()),
ScaleInBottom(new ScaleInBottomAnimator()),
ScaleInLeft(new ScaleInLeftAnimator()),
ScaleInRight(new ScaleInRightAnimator()),
FlipInTopX(new FlipInTopXAnimator()),
FlipInBottomX(new FlipInBottomXAnimator()),
FlipInLeftY(new FlipInLeftYAnimator()),
FlipInRightY(new FlipInRightYAnimator()),
SlideInLeft(new SlideInLeftAnimator()),
SlideInRight(new SlideInRightAnimator()),
SlideInDown(new SlideInDownAnimator()),
SlideInUp(new SlideInUpAnimator()),
OvershootInRight(new OvershootInRightAnimator()),
OvershootInLeft(new OvershootInLeftAnimator());
private BaseItemAnimator mAnimator;
Type(BaseItemAnimator animator) {
mAnimator = animator;
}
public BaseItemAnimator getAnimator() {
return mAnimator;
}
}*/
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/DebugNoHeaderLoadMoreActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import android.view.LayoutInflater;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import java.util.ArrayList;
/**
* Created by hesk on 19/2/16.
*/
public class DebugNoHeaderLoadMoreActivity extends BasicFunctions {
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
@Override
protected void enableEmptyViewPolicy() {
ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
}
@Override
protected void onLoadmore() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 2);
}
@Override
protected void onFireRefresh() {
// simpleRecyclerViewAdapter.insertLast(moreNum++ + " Refresh things");
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
// linearLayoutManager.scrollToPosition(0);
ultimateRecyclerView.scrollVerticallyTo(0);
//ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
//simpleRecyclerViewAdapter.notifyDataSetChanged();
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.disableLoadmore();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void doURV(UltimateRecyclerView ultimateRecyclerView) {
// ultimateRecyclerView.setInflater(LayoutInflater.from(getApplicationContext()));
ultimateRecyclerView.setHasFixedSize(false);
ArrayList list = new ArrayList<>();
list.add("o2fn31");
list.add("of2n32");
list.add("of3n36");
simpleRecyclerViewAdapter = new sectionZeroAdapter(list);
configLinearLayoutManager(ultimateRecyclerView);
//enableParallaxHeader();
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ff4fcccf"));
enableRefresh();
// enableScrollControl();
// enableSwipe();
// enableItemClick();
ultimateRecyclerView.setItemViewCacheSize(simpleRecyclerViewAdapter.getAdditionalItems());
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
@Override
protected void addButtonTrigger() {
simpleRecyclerViewAdapter.insertLast("++ new Item");
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeLast();
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/FinalEmptyViewDisplayActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;
import java.util.ArrayList;
/**
* Created by hesk on 25/2/16.
*/
public class FinalEmptyViewDisplayActivity extends BasicFunctions implements emptyViewOnShownListener {
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
private Handler time_count = new Handler();
private int time = 0;
@Override
protected void onLoadmore() {
time_count.postDelayed(new Runnable() {
@Override
public void run() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 5);
}
}, 1000);
}
@Override
protected void onFireRefresh() {
time_count.postDelayed(new Runnable() {
@Override
public void run() {
ultimateRecyclerView.setRefreshing(false);
}
}, 1000);
}
@Override
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
ultimateRecyclerView.setEmptyView(R.layout.empty_view_v2, UltimateRecyclerView.EMPTY_CLEAR_ALL, this);
}
@Override
protected void doURV(UltimateRecyclerView urv) {
ultimateRecyclerView.setHasFixedSize(false);
simpleRecyclerViewAdapter = new sectionZeroAdapter(new ArrayList());
configLinearLayoutManager(ultimateRecyclerView);
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ff4fcccf"));
enableRefresh();
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
@Override
protected void addButtonTrigger() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 3);
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void toggleButtonTrigger() {
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.showEmptyView();
ultimateRecyclerView.disableLoadmore();
}
@Override
public void onEmptyViewShow(View mView) {
TextView tv = (TextView) mView.findViewById(R.id.exp_section_title);
if (tv != null) {
StringBuilder sb = new StringBuilder();
sb.append("Your pressed at \"");
sb.append(time);
sb.append("\" and that is not found.");
tv.setText(sb.toString());
}
time++;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/FirstPageCancelLoadMore.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import android.os.Handler;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import java.util.ArrayList;
/**
* Created by hesk on 25/2/16.
*/
public class FirstPageCancelLoadMore extends BasicFunctions {
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
private Handler time_count = new Handler();
@Override
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
}
@Override
protected void onLoadmore() {
time_count.postDelayed(new Runnable() {
@Override
public void run() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 2);
ultimateRecyclerView.disableLoadmore();
}
}, 1000);
}
@Override
protected void onFireRefresh() {
// simpleRecyclerViewAdapter.insertLast(moreNum++ + " Refresh things");
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
//ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
//simpleRecyclerViewAdapter.notifyDataSetChanged();
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.disableLoadmore();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void doURV(UltimateRecyclerView urv) {
ultimateRecyclerView.setHasFixedSize(false);
simpleRecyclerViewAdapter = new sectionZeroAdapter(new ArrayList());
configLinearLayoutManager(ultimateRecyclerView);
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ff4fcccf"));
enableRefresh();
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
@Override
protected void addButtonTrigger() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 3);
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeAll();
}
@Override
protected void toggleButtonTrigger() {
if (!status_progress) {
isEnableAutoLoadMore = !isEnableAutoLoadMore;
if (isEnableAutoLoadMore) {
ultimateRecyclerView.reenableLoadmore();
}
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/LineNodeActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import android.os.Handler;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.modules.TimeLineModel;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.TimeLineAdapter;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Created by zJJ on 4/27/2016.
*/
public class LineNodeActivity extends BasicFunctions {
@Override
protected void onLoadmore() {
}
@Override
protected void onFireRefresh() {
}
public static void insertMoreWhole(easyRegularAdapter sd, int howmany) {
ArrayList items = new ArrayList<>();
addAmount(howmany, items);
/**
* additional patch for the additional item
*/
int at = sd.getAdapterItemCount();
sd.insert(items);
sd.notifyDataSetChanged();
}
protected static void addAmount(int howMany, ArrayList list) {
for (int i = 0; i < howMany; i++) {
UUID uuid = UUID.randomUUID();
TimeLineModel time = new TimeLineModel();
time.setAge(uuid.variant());
time.setName(uuid.toString());
list.add(time);
}
}
@Override
protected void addButtonTrigger() {
insertMoreWhole(simpleRecyclerViewAdapter, 3);
}
@Override
protected void removeButtonTrigger() {
}
private TimeLineAdapter simpleRecyclerViewAdapter = null;
private Handler time_count = new Handler();
@Override
protected void doURV(UltimateRecyclerView urv) {
ArrayList list = new ArrayList<>();
TimeLineModel time = new TimeLineModel();
time.setAge(139);
time.setName("England");
list.add(time);
TimeLineModel time2 = new TimeLineModel();
time2.setAge(359);
time2.setName("Japan");
list.add(time2);
TimeLineModel time3 = new TimeLineModel();
time3.setAge(339);
time3.setName("HK");
list.add(time3);
addAmount(29, list);
ultimateRecyclerView.setHasFixedSize(true);
simpleRecyclerViewAdapter = new TimeLineAdapter(list);
//currently we only support linearlayout option but we have tested anything for the grid layout yet
configLinearLayoutManager(ultimateRecyclerView);
enableEmptyViewPolicy();
// enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ff6f36cf"));
//enableRefresh();
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/PullToRefreshActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.widget.Toolbar;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.CustomUltimateRecyclerview;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
public class PullToRefreshActivity extends BasicFunctions implements ActionMode.Callback {
private CustomUltimateRecyclerview ultimateRecyclerView;
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
private View floatingButton = null;
@Override
protected void onLoadmore() {
}
@Override
protected void onFireRefresh() {
// simpleRecyclerViewAdapter.insertLast("Refresh things");
// ultimateRecyclerView.scrollBy(0, -50);
// linearLayoutManager.scrollToPosition(0);
ultimateRecyclerView.mPtrFrameLayout.refreshComplete();
changeHeaderHandler.sendEmptyMessageDelayed(0, 500);
}
@Override
protected void addButtonTrigger() {
}
@Override
protected void removeButtonTrigger() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_refresh_activity);
ultimateRecyclerView = (CustomUltimateRecyclerview) findViewById(R.id.custom_ultimate_recycler_view);
ultimateRecyclerView.setCustomSwipeToRefresh();
// refreshingMaterial();
refreshingString();
}
void refreshingString() {
storeHouseHeader = new StoreHouseHeader(this);
// header.setPadding(0, 15, 0, 0);
storeHouseHeader.initWithString("XCode Big Air");
// header.initWithStringArray(R.array.akta);
ultimateRecyclerView.mPtrFrameLayout.removePtrUIHandler(materialHeader);
ultimateRecyclerView.mPtrFrameLayout.setHeaderView(storeHouseHeader);
ultimateRecyclerView.mPtrFrameLayout.addPtrUIHandler(storeHouseHeader);
ultimateRecyclerView.mPtrFrameLayout.autoRefresh(false);
ultimateRecyclerView.mPtrFrameLayout.setPtrHandler(new PtrHandler() {
@Override
public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view2) {
boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view2);
return canbePullDown;
}
@Override
public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
ptrFrameLayout.postDelayed(new Runnable() {
@Override
public void run() {
onFireRefresh();
}
}, 1800);
}
});
}
// void refreshingRental() {
// rentalsSunHeaderView = new RentalsSunHeaderView(this);
// rentalsSunHeaderView.setUp(ultimateRecyclerView.mPtrFrameLayout);
//
// ultimateRecyclerView.mPtrFrameLayout.removePtrUIHandler(materialHeader);
// ultimateRecyclerView.mPtrFrameLayout.removePtrUIHandler(storeHouseHeader);
// ultimateRecyclerView.mPtrFrameLayout.setHeaderView(rentalsSunHeaderView);
// ultimateRecyclerView.mPtrFrameLayout.addPtrUIHandler(rentalsSunHeaderView);
// ultimateRecyclerView.mPtrFrameLayout.autoRefresh(false);
// ultimateRecyclerView.mPtrFrameLayout.setPtrHandler(new PtrHandler() {
// @Override
// public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view2) {
// boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view2);
// return canbePullDown;
// }
//
// @Override
// public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
// ptrFrameLayout.postDelayed(new Runnable() {
// @Override
// public void run() {
// simpleRecyclerViewAdapter.insert("Refresh things", 0);
// // ultimateRecyclerView.scrollBy(0, -50);
// linearLayoutManager.scrollToPosition(0);
// ultimateRecyclerView.mPtrFrameLayout.refreshComplete();
// changeHeaderHandler.sendEmptyMessageDelayed(3, 500);
// }
// }, 1800);
// }
// });
//
// }
void refreshingMaterial() {
materialHeader = new MaterialHeader(this);
int[] colors = getResources().getIntArray(R.array.google_colors);
materialHeader.setColorSchemeColors(colors);
materialHeader.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
materialHeader.setPadding(0, 15, 0, 10);
materialHeader.setPtrFrameLayout(ultimateRecyclerView.mPtrFrameLayout);
ultimateRecyclerView.mPtrFrameLayout.autoRefresh(false);
ultimateRecyclerView.mPtrFrameLayout.removePtrUIHandler(storeHouseHeader);
ultimateRecyclerView.mPtrFrameLayout.setHeaderView(materialHeader);
ultimateRecyclerView.mPtrFrameLayout.addPtrUIHandler(materialHeader);
ultimateRecyclerView.mPtrFrameLayout.setPtrHandler(new PtrHandler() {
@Override
public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
return true;
}
@Override
public void onRefreshBegin(final PtrFrameLayout frame) {
frame.postDelayed(new Runnable() {
@Override
public void run() {
// simpleRecyclerViewAdapter.insertLast("Refresh things");
// ultimateRecyclerView.scrollBy(0, -50);
// linearLayoutManager.scrollToPosition(0);
ultimateRecyclerView.mPtrFrameLayout.refreshComplete();
// changeHeaderHandler.sendEmptyMessageDelayed(2, 500);
}
}, 1800);
}
});
}
Handler changeHeaderHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
refreshingStringArray();
break;
case 1:
// refreshingMaterial();
refreshingString();
break;
case 2:
// refreshingString();
break;
case 3:
refreshingString();
break;
case 4:
break;
}
}
};
private int mLoadTime = 0;
StoreHouseHeader storeHouseHeader;
MaterialHeader materialHeader;
// RentalsSunHeaderView rentalsSunHeaderView;
private void refreshingStringArray() {
storeHouseHeader = new StoreHouseHeader(this);
storeHouseHeader.setPadding(0, 15, 0, 0);
// using string array from resource xml file
storeHouseHeader.initWithStringArray(R.array.storehouse);
ultimateRecyclerView.mPtrFrameLayout.setDurationToCloseHeader(1500);
ultimateRecyclerView.mPtrFrameLayout.removePtrUIHandler(materialHeader);
ultimateRecyclerView.mPtrFrameLayout.setHeaderView(storeHouseHeader);
ultimateRecyclerView.mPtrFrameLayout.addPtrUIHandler(storeHouseHeader);
ultimateRecyclerView.mPtrFrameLayout.autoRefresh(false);
// change header after loaded
ultimateRecyclerView.mPtrFrameLayout.addPtrUIHandler(new PtrUIHandler() {
@Override
public void onUIReset(PtrFrameLayout frame) {
mLoadTime++;
if (mLoadTime % 2 == 0) {
storeHouseHeader.setScale(1);
storeHouseHeader.initWithStringArray(R.array.storehouse);
} else {
storeHouseHeader.setScale(0.5f);
storeHouseHeader.initWithStringArray(R.array.akta);
}
}
@Override
public void onUIRefreshPrepare(PtrFrameLayout frame) {
}
@Override
public void onUIRefreshBegin(PtrFrameLayout frame) {
}
@Override
public void onUIRefreshComplete(PtrFrameLayout frame) {
}
@Override
public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
}
});
ultimateRecyclerView.mPtrFrameLayout.setPtrHandler(new PtrHandler() {
@Override
public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
return true;
}
@Override
public void onRefreshBegin(final PtrFrameLayout frame) {
frame.postDelayed(new Runnable() {
@Override
public void run() {
// frame.refreshComplete();
// simpleRecyclerViewAdapter.insertLast("Refresh things");
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
ultimateRecyclerView.mPtrFrameLayout.refreshComplete();
if (mLoadTime % 2 == 0)
changeHeaderHandler.sendEmptyMessageDelayed(1, 500);
}
}, 2000);
}
});
}
private void toggleSelection(int position) {
simpleRecyclerViewAdapter.toggleSelection(position);
actionMode.setTitle("Selected " + "1");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
@Override
protected void doURV(UltimateRecyclerView urv) {
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
URLogs.d("actionmode---" + (mode == null));
mode.getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
// return false;
}
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
*
* @param mode ActionMode being prepared
* @param menu Menu used to populate action buttons
* @return true if the menu or action mode was updated, false otherwise.
*/
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// swipeToDismissTouchListener.setEnabled(false);
this.actionMode = mode;
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
this.actionMode = null;
}
//
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}
/*
enum Type {
FadeIn("FadeIn", new FadeInAnimator()),
FadeInDown("FadeInDown", new FadeInDownAnimator()),
FadeInUp("FadeInUp", new FadeInUpAnimator()),
FadeInLeft("FadeInLeft", new FadeInLeftAnimator()),
FadeInRight("FadeInRight", new FadeInRightAnimator()),
Landing("Landing", new LandingAnimator()),
ScaleIn("ScaleIn", new ScaleInAnimator()),
ScaleInTop("ScaleInTop", new ScaleInTopAnimator()),
ScaleInBottom("ScaleInBottom", new ScaleInBottomAnimator()),
ScaleInLeft("ScaleInLeft", new ScaleInLeftAnimator()),
ScaleInRight("ScaleInRight", new ScaleInRightAnimator()),
FlipInTopX("FlipInTopX", new FlipInTopXAnimator()),
FlipInBottomX("FlipInBottomX", new FlipInBottomXAnimator()),
FlipInLeftY("FlipInLeftY", new FlipInLeftYAnimator()),
FlipInRightY("FlipInRightY", new FlipInRightYAnimator()),
SlideInLeft("SlideInLeft", new SlideInLeftAnimator()),
SlideInRight("SlideInRight", new SlideInRightAnimator()),
SlideInDown("SlideInDown", new SlideInDownAnimator()),
SlideInUp("SlideInUp", new SlideInUpAnimator()),
OvershootInRight("OvershootInRight", new OvershootInRightAnimator()),
OvershootInLeft("OvershootInLeft", new OvershootInLeftAnimator());
private String mTitle;
private BaseItemAnimator mAnimator;
Type(String title, BaseItemAnimator animator) {
mTitle = title;
mAnimator = animator;
}
public BaseItemAnimator getAnimator() {
return mAnimator;
}
public String getTitle() {
return mTitle;
}
}
*/
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/Route.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.content.Context;
import android.content.Intent;
/**
* Created by hesk on 24/2/16.
*/
public enum Route {
LineNodeActivity("LineNodeActivity", LineNodeActivity.class),
STAGGER_LOAD_MORE("Stagger LoadMore", StaggerLoadMoreActivity.class),
LOADLOADING_CUT("Stop loading", FirstPageCancelLoadMore.class),
LOADMORE_TEST("No Header", DebugNoHeaderLoadMoreActivity.class),
FinalEmptyViewDisplayActivity("Empty View", FinalEmptyViewDisplayActivity.class),
SLIDER_HEADER("Header of Slider", SliderHeader.class),
SWIPE_LIST("Swipe List View Example", SwipeListViewExampleActivity.class),
LOADMORE_HEADER("Header Pallx", DebugLoadMoreActivity.class),;
private String name;
private Class> clazzna;
Route(String name, Class> clazz) {
this.name = name;
this.clazzna = clazz;
}
public Route getAnimator() {
return this;
}
public String getNameDisplay() {
return name;
}
public void start(final Context ctx) {
Intent intent = new Intent(ctx, clazzna);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/SliderHeader.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import com.hkm.slider.SliderLayout;
import com.hkm.slider.SliderTypes.BaseSliderView;
import com.hkm.slider.SliderTypes.TextSliderView;
import com.hkm.slider.TransformerL;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import java.util.ArrayList;
/**
* Created by hesk on 18/3/16.
*/
public class SliderHeader extends BasicFunctions implements BaseSliderView.OnSliderClickListener {
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
@Override
protected void onLoadmore() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 2);
}
@Override
protected void onFireRefresh() {
// simpleRecyclerViewAdapter.insertLast(moreNum++ + " Refresh things");
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
//ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
//simpleRecyclerViewAdapter.notifyDataSetChanged();
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.disableLoadmore();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void addButtonTrigger() {
simpleRecyclerViewAdapter.insertFirst("rand added item");
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeLast();
}
@Override
protected void doURV(UltimateRecyclerView urv) {
ultimateRecyclerView.setHasFixedSize(false);
simpleRecyclerViewAdapter = new sectionZeroAdapter(new ArrayList());
configLinearLayoutManager(ultimateRecyclerView);
enableParallaxHeader();
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffff66ff"));
enableRefresh();
// enableScrollControl();
// enableSwipe();
// enableItemClick();
ultimateRecyclerView.setItemViewCacheSize(simpleRecyclerViewAdapter.getAdditionalItems());
ultimateRecyclerView.setNormalHeader(initSlider(ultimateRecyclerView));
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
private View initSlider(UltimateRecyclerView listview) {
final View view = LayoutInflater.from(getApplication()).inflate(R.layout.list_item_header, null, false);
final ViewTreeObserver vto = listview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//Log.d("vto", "globallayout");
final SliderLayout sl = (SliderLayout) view.findViewById(R.id.header_slider);
try {
sl.setOffscreenPageLimit(1);
sl.setSliderTransformDuration(500, new LinearOutSlowInInterpolator());
sl.setPresetTransformer(TransformerL.Default);
sl.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
sl.getPagerIndicator().setDefaultIndicatorColor(R.color.accent, R.color.primaryDark);
sl.getPagerIndicator().setVisibility(View.GONE);
setup_double_faces(sl);
} catch (Exception e) {
e.printStackTrace();
}
}
});
return view;
}
String[] urls = {
// "http://pcdn.500px.net/35939982/127d53ceac436e2e17a11ea42bb2cd7719b9f1e1/4.jpg",
"http://cs407831.userapi.com/v4078f31207/18fe/4Tz8av5Hlvo.jpg",
// special url with error
"http://cs407831.userapi.com/v407831207/1906/oxoP6URjFtA.jpg",
"http://cs407831.userapi.com/v407831207/190e/2Sz9A774hUc.jpg",
"http://cs407831.userapi.com/v407831207/1916/Ua52RjnKqjk.jpg",
"http://cs407831.userapi.com/v407831207/190e/2Sz9A774hUc.jpg",
"http://cs407831.userapi.com/v407831207/1916/Ua52RjnKqjk.jpg",
"http://cs407831.userapi.com/v407831207/190e/2Sz9A774hUc.jpg",
"http://cs407831.userapi.com/v407831207/1916/Ua52RjnKqjk.jpg",
"http://cs407831.userapi.com/v407831207/191e/QEQE83Ok0lQ.jpg"
};
protected void setup_double_faces(final SliderLayout mslide) throws Exception {
ArrayList ie = new ArrayList<>();
// mslide.setCustomAnimation(new DescriptionAnimation(250, new DecelerateInterpolator()));
for (int i = 0; i < urls.length; i++) {
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView
.image(urls[i])
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
ie.add(textSliderView);
}
mslide.loadSliderList(ie);
}
@Override
public void onSliderClick(BaseSliderView coreSlider) {
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/StaggerLoadMoreActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.staggerAdapter;
import java.util.ArrayList;
/**
* Created by hesk on 5/4/16.
*/
public class StaggerLoadMoreActivity extends BasicFunctions {
staggerAdapter simpleRecyclerViewAdapter = null;
@Override
protected void onLoadmore() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 7);
}
@Override
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
}
@Override
protected void onFireRefresh() {
// simpleRecyclerViewAdapter.insertLast(moreNum++ + " Refresh things");
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
//ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
//simpleRecyclerViewAdapter.notifyDataSetChanged();
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.disableLoadmore();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void doURV(UltimateRecyclerView urv) {
ultimateRecyclerView.setHasFixedSize(false);
simpleRecyclerViewAdapter = new staggerAdapter(new ArrayList());
//configLinearLayoutManager(ultimateRecyclerView);
configStaggerLayoutManager(ultimateRecyclerView, simpleRecyclerViewAdapter);
// enableParallaxHeader();
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ff4fcccf"));
enableRefresh();
// enableScrollControl();
// enableSwipe();
// enableItemClick();
ultimateRecyclerView.setItemViewCacheSize(simpleRecyclerViewAdapter.getAdditionalItems());
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
@Override
protected void addButtonTrigger() {
simpleRecyclerViewAdapter.insertLast("++ New Item");
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeLast();
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/loadmoredemo/SwipeListViewExampleActivity.java
================================================
/*
* Copyright (C) 2013 47 Degrees, LLC
* http://47deg.com
* hello@47deg.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.SwipeAdapter;
import com.marshalchen.ultimaterecyclerview.layoutmanagers.ScrollSmoothLineaerLayoutManager;
import com.marshalchen.ultimaterecyclerview.swipe.SwipeItemManagerInterface;
import java.util.ArrayList;
import java.util.List;
public class SwipeListViewExampleActivity extends BasicFunctions {
private SwipeAdapter adapter;
private List data;
private ScrollSmoothLineaerLayoutManager mLayoutManager;
@Override
protected void onLoadmore() {
SampleDataboxset.insertMoreWhole(adapter, 3);
}
@Override
protected void onFireRefresh() {
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
//ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
//simpleRecyclerViewAdapter.notifyDataSetChanged();
adapter.removeAll();
ultimateRecyclerView.disableLoadmore();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void addButtonTrigger() {
adapter.insertLast("++ xxx");
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
adapter.removeLast();
}
@Override
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
}
@Override
protected void doURV(UltimateRecyclerView urv) {
data = new ArrayList();
data.add("aa");
data.add("bb");
data.add("cc");
data.add("dd");
data.add("aa");
data.add("bb");
data.add("cc");
data.add("dd");
data.add("aa");
data.add("bb");
data.add("cc");
data.add("dd");
enableEmptyViewPolicy();
enableLoadMore();
enableRefresh();
adapter = new SwipeAdapter(data);
adapter.setMode(SwipeItemManagerInterface.Mode.Single);
mLayoutManager = new ScrollSmoothLineaerLayoutManager(this, LinearLayoutManager.VERTICAL, false, 500);
ultimateRecyclerView.setHasFixedSize(false);
ultimateRecyclerView.setLayoutManager(mLayoutManager);
// swipeListView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
// @Override
// public void onItemClick(View view, int position) {
// URLogs.d("click");
// }
// }));
ultimateRecyclerView.setAdapter(adapter);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/AbstractDataProvider.java
================================================
/*
* Copyright (C) 2015 Haruki Hasegawa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.demo.modules;
public abstract class AbstractDataProvider {
public static abstract class Data {
public abstract long getId();
public abstract boolean isSectionHeader();
public abstract int getViewType();
public abstract int getSwipeReactionType();
public abstract String getText();
public abstract void setPinnedToSwipeLeft(boolean pinned);
public abstract boolean isPinnedToSwipeLeft();
}
public abstract int getCount();
public abstract Data getItem(int index);
public abstract void removeItem(int position);
public abstract void moveItem(int fromPosition, int toPosition);
public abstract int undoLastRemoval();
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/CircularImageView.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import com.marshalchen.ultimaterecyclerview.demo.R;
/**
* Custom ImageView for circular images in Android while maintaining the
* best draw performance and supporting custom borders & selectors.
*/
public class CircularImageView extends ImageView {
// For logging purposes
private static final String TAG = CircularImageView.class.getSimpleName();
// Default property values
private static final boolean SHADOW_ENABLED = false;
private static final float SHADOW_RADIUS = 4f;
private static final float SHADOW_DX = 0f;
private static final float SHADOW_DY = 2f;
private static final int SHADOW_COLOR = Color.BLACK;
// Border & Selector configuration variables
private boolean hasBorder;
private boolean hasSelector;
private boolean isSelected;
private int borderWidth;
private int canvasSize;
private int selectorStrokeWidth;
// Shadow properties
private boolean shadowEnabled;
private float shadowRadius;
private float shadowDx;
private float shadowDy;
private int shadowColor;
// Objects used for the actual drawing
private BitmapShader shader;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private Paint paintSelectorBorder;
private ColorFilter selectorFilter;
public CircularImageView(Context context) {
this(context, null,
R.styleable.CircularImageViewStyle_circularImageViewDefault);
}
public CircularImageView(Context context, AttributeSet attrs) {
this(context, attrs, R.styleable.CircularImageViewStyle_circularImageViewDefault);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CircularImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr);
}
/**
* Initializes paint objects and sets desired attributes.
* @param context Context
* @param attrs Attributes
* @param defStyle Default Style
*/
private void init(Context context, AttributeSet attrs, int defStyle) {
// Initialize paint objects
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
paintBorder.setStyle(Paint.Style.STROKE);
paintSelectorBorder = new Paint();
paintSelectorBorder.setAntiAlias(true);
// Enable software rendering on HoneyComb and up. (needed for shadow)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
setLayerType(LAYER_TYPE_SOFTWARE, null);
// Load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
// Check for extra features being enabled
hasBorder = attributes.getBoolean(R.styleable.CircularImageView_civ_border, false);
hasSelector = attributes.getBoolean(R.styleable.CircularImageView_civ_selector, false);
shadowEnabled = attributes.getBoolean(R.styleable.CircularImageView_civ_shadow, SHADOW_ENABLED);
// Set border properties, if enabled
if(hasBorder) {
int defaultBorderSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_civ_borderWidth, defaultBorderSize));
setBorderColor(attributes.getColor(R.styleable.CircularImageView_civ_borderColor, Color.WHITE));
}
// Set selector properties, if enabled
if(hasSelector) {
int defaultSelectorSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setSelectorColor(attributes.getColor(R.styleable.CircularImageView_civ_selectorColor, Color.TRANSPARENT));
setSelectorStrokeWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_civ_selectorStrokeWidth, defaultSelectorSize));
setSelectorStrokeColor(attributes.getColor(R.styleable.CircularImageView_civ_selectorStrokeColor, Color.BLUE));
}
// Set shadow properties, if enabled
if(shadowEnabled) {
shadowRadius = attributes.getFloat(R.styleable.CircularImageView_civ_shadowRadius, SHADOW_RADIUS);
shadowDx = attributes.getFloat(R.styleable.CircularImageView_civ_shadowDx, SHADOW_DX);
shadowDy = attributes.getFloat(R.styleable.CircularImageView_civ_shadowDy, SHADOW_DY);
shadowColor = attributes.getColor(R.styleable.CircularImageView_civ_shadowColor, SHADOW_COLOR);
setShadowEnabled(true);
}
// We no longer need our attributes TypedArray, give it back to cache
attributes.recycle();
}
/**
* Sets the CircularImageView's border width in pixels.
* @param borderWidth Width in pixels for the border.
*/
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
if(paintBorder != null)
paintBorder.setStrokeWidth(borderWidth);
requestLayout();
invalidate();
}
/**
* Sets the CircularImageView's basic border color.
* @param borderColor The new color (including alpha) to set the border.
*/
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
/**
* Sets the color of the selector to be draw over the
* CircularImageView. Be sure to provide some opacity.
* @param selectorColor The color (including alpha) to set for the selector overlay.
*/
public void setSelectorColor(int selectorColor) {
this.selectorFilter = new PorterDuffColorFilter(selectorColor, PorterDuff.Mode.SRC_ATOP);
this.invalidate();
}
/**
* Sets the stroke width to be drawn around the CircularImageView
* during click events when the selector is enabled.
* @param selectorStrokeWidth Width in pixels for the selector stroke.
*/
public void setSelectorStrokeWidth(int selectorStrokeWidth) {
this.selectorStrokeWidth = selectorStrokeWidth;
this.requestLayout();
this.invalidate();
}
/**
* Sets the stroke color to be drawn around the CircularImageView
* during click events when the selector is enabled.
* @param selectorStrokeColor The color (including alpha) to set for the selector stroke.
*/
public void setSelectorStrokeColor(int selectorStrokeColor) {
if (paintSelectorBorder != null)
paintSelectorBorder.setColor(selectorStrokeColor);
this.invalidate();
}
/**
* Enables a dark shadow for this CircularImageView.
* @param enabled Set to true to draw a shadow or false to disable it.
*/
public void setShadowEnabled(boolean enabled) {
shadowEnabled = enabled;
updateShadow();
}
/**
* Enables a dark shadow for this CircularImageView.
* If the radius is set to 0, the shadow is removed.
* @param radius Radius for the shadow to extend to.
* @param dx Horizontal shadow offset.
* @param dy Vertical shadow offset.
* @param color The color of the shadow to apply.
*/
public void setShadow(float radius, float dx, float dy, int color) {
shadowRadius = radius;
shadowDx = dx;
shadowDy = dy;
shadowColor = color;
updateShadow();
}
@Override
public void onDraw(Canvas canvas) {
// Don't draw anything without an image
if(image == null)
return;
// Nothing to draw (Empty bounds)
if(image.getHeight() == 0 || image.getWidth() == 0)
return;
// Update shader if canvas size has changed
int oldCanvasSize = canvasSize;
canvasSize = getWidth() < getHeight() ? getWidth() : getHeight();
if(oldCanvasSize != canvasSize)
updateBitmapShader();
// Apply shader to paint
paint.setShader(shader);
// Keep track of selectorStroke/border width
int outerWidth = 0;
// Get the exact X/Y axis of the view
int center = canvasSize / 2;
if(hasSelector && isSelected) { // Draw the selector stroke & apply the selector filter, if applicable
outerWidth = selectorStrokeWidth;
center = (canvasSize - (outerWidth * 2)) / 2;
paint.setColorFilter(selectorFilter);
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, paintSelectorBorder);
}
else if(hasBorder) { // If no selector was drawn, draw a border and clear the filter instead... if enabled
outerWidth = borderWidth;
center = (canvasSize - (outerWidth * 2)) / 2;
paint.setColorFilter(null);
RectF rekt = new RectF(0 + outerWidth / 2, 0 + outerWidth / 2, canvasSize - outerWidth / 2, canvasSize - outerWidth / 2);
canvas.drawArc(rekt, 360, 360, false, paintBorder);
//canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, paintBorder);
}
else // Clear the color filter if no selector nor border were drawn
paint.setColorFilter(null);
// Draw the circular image itself
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2), paint);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// Check for clickable state and do nothing if disabled
if(!this.isClickable()) {
this.isSelected = false;
return super.onTouchEvent(event);
}
// Set selected state based on Motion Event
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
this.isSelected = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_SCROLL:
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_CANCEL:
this.isSelected = false;
break;
}
// Redraw image and return super type
this.invalidate();
return super.dispatchTouchEvent(event);
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
// Extract a Bitmap out of the drawable & set it as the main shader
image = drawableToBitmap(getDrawable());
if(canvasSize > 0)
updateBitmapShader();
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
// Extract a Bitmap out of the drawable & set it as the main shader
image = drawableToBitmap(getDrawable());
if(canvasSize > 0)
updateBitmapShader();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
// Extract a Bitmap out of the drawable & set it as the main shader
image = drawableToBitmap(getDrawable());
if(canvasSize > 0)
updateBitmapShader();
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
// Extract a Bitmap out of the drawable & set it as the main shader
image = bm;
if(canvasSize > 0)
updateBitmapShader();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
}
else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
}
else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
private int measureHeight(int measureSpecHeight) {
int result;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
// TODO: Update shadow layers based on border/selector state and visibility.
private void updateShadow() {
final float radius = shadowEnabled ? shadowRadius : 0;
//paint.setShadowLayer(radius, shadowDx, shadowDy, shadowColor);
paintBorder.setShadowLayer(radius, shadowDx, shadowDy, shadowColor);
paintSelectorBorder.setShadowLayer(radius, shadowDx, shadowDy, shadowColor);
}
/**
* Convert a drawable object into a Bitmap.
* @param drawable Drawable to extract a Bitmap from.
* @return A Bitmap created from the drawable parameter.
*/
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) // Don't do anything without a proper drawable
return null;
else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable
Log.i(TAG, "Bitmap drawable!");
return ((BitmapDrawable) drawable).getBitmap();
}
int intrinsicWidth = drawable.getIntrinsicWidth();
int intrinsicHeight = drawable.getIntrinsicHeight();
if (!(intrinsicWidth > 0 && intrinsicHeight > 0))
return null;
try {
// Create Bitmap object out of the drawable
Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
// Simply return null of failed bitmap creations
Log.e(TAG, "Encountered OutOfMemoryError while generating bitmap!");
return null;
}
}
// TODO TEST REMOVE
public void setIconModeEnabled(final boolean e) {}
/**
* Re-initializes the shader texture used to fill in
* the Circle upon drawing.
*/
public void updateBitmapShader() {
if (image == null)
return;
shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) {
Matrix matrix = new Matrix();
float scale = (float) canvasSize / (float) image.getWidth();
matrix.setScale(scale, scale);
shader.setLocalMatrix(matrix);
}
}
/**
* @return Whether or not this view is currently
* in its selected state.
*/
public boolean isSelected() {
return this.isSelected;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/FastBinding.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.IdRes;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.PullToRefreshActivity;
import com.marshalchen.ultimaterecyclerview.demo.griddemo.GridLayoutRVTest;
import com.marshalchen.ultimaterecyclerview.demo.multiitemdemo.MultiViewTypesActivity;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.admobdemo.TestAdMobClassicActivity;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.DebugLoadMoreActivity;
import com.marshalchen.ultimaterecyclerview.demo.admobdemo.TestAdvancedAdmobActivity;
import com.marshalchen.ultimaterecyclerview.demo.scrollableobservable.ScrollObservablesActivity;
import com.marshalchen.ultimaterecyclerview.demo.expandemo.TestExpandableRV;
import com.marshalchen.ultimaterecyclerview.demo.loadmoredemo.SwipeListViewExampleActivity;
/**
* Created by hesk on 7/1/2015.
*/
public enum FastBinding {
action_bottom(R.id.action_bottom, MultiViewTypesActivity.class),
action_custom(R.id.action_custom, PullToRefreshActivity.class),
admob(R.id.admob, TestAdMobClassicActivity.class),
scrollactivity(R.id.scrollactivity, ScrollObservablesActivity.class),
swipe_and_drag(R.id.swipe_and_drag, SwipeListViewExampleActivity.class),
debug_load_more(R.id.debug_load_more, DebugLoadMoreActivity.class),
advancedAdmob(R.id.adv_admob, TestAdvancedAdmobActivity.class),
gridlayouttesting(R.id.gridlayoutperformance, GridLayoutRVTest.class),
expandmenu(R.id.expandmenu, TestExpandableRV.class);
private int id;
private Class> clazz;
FastBinding(final @IdRes int id, Class> clazz) {
this.id = id;
this.clazz = clazz;
}
public Class> getClassName() {
return clazz;
}
public int getId() {
return id;
}
public static void startactivity(final Context ctx, final @IdRes int id) {
final int g = FastBinding.values().length;
for (int i = 0; i < g; i++) {
FastBinding bind = FastBinding.values()[i];
if (bind.getId() == id) {
Intent intent = new Intent(ctx, bind.getClassName());
ctx.startActivity(intent);
return;
}
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/JRitem.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
import androidx.annotation.DrawableRes;
/**
* Created by hesk on 3/2/16.
*/
public class JRitem {
@DrawableRes
public final int photo_id;
public final String train_name;
public JRitem(@DrawableRes final int photo_idjr, String name) {
photo_id = photo_idjr;
train_name = name;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/MainWatcher.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
import android.app.Application;
import android.content.pm.ApplicationInfo;
/**
* Created by hesk on 2/10/15.
*/
public class MainWatcher extends Application {
@Override
public void onCreate() {
super.onCreate();
//CrashWoodpecker.fly().to(this);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/SampleDataboxset.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.admobdemo.ZeroStickyAdvertistmentAdapter;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by hesk on 7/1/2015.
*/
public class SampleDataboxset {
public static List newList() {
final List stringList = new ArrayList<>();
stringList.add("111");
stringList.add("TYAT");
stringList.add("BMW");
stringList.add("3M");
stringList.add("Apple");
stringList.add("Organe");
stringList.add("Nike");
stringList.add("Addos");
stringList.add("76 RE");
return stringList;
}
public static List newList(int longh) {
final List j = newList();
genItems(longh, j);
return j;
}
public static List newListFromGen(int n) {
final List s = new ArrayList<>();
genItems(n, s);
return s;
}
public static List newListFromGen() {
final List s = new ArrayList<>();
genItems(38, s);
return s;
}
public static void genItems(final int howmany, final List list) {
for (int i = 0; i < howmany; i++) {
Random e = new Random();
list.add("No." + i + " " + girl_name[e.nextInt(girl_name.length)]);
}
}
public static void insertMore(easyRegularAdapter sd, int howmany) {
for (int i = 0; i < howmany; i++) {
sd.insertLast("More ** " + i);
}
}
public static void insertMoreWhole(easyRegularAdapter sd, int howmany) {
List items = new ArrayList<>();
for (int i = 0; i < howmany; i++) {
items.add("More ** " + i);
}
sd.insert(items);
}
public static List genJRList(int counts) {
List items = new ArrayList<>();
for (int i = 0; i < counts; i++) {
items.add(genJRSingle());
}
return items;
}
public static JRitem genJRSingle() {
Random e = new Random();
JRitem bodu = new JRitem(SampleDataboxset.getGirlImageRandom(), girl_name[e.nextInt(girl_name.length)]);
return bodu;
}
public static int getGirlImageRandom() {
Random e = new Random();
return res[e.nextInt(res.length)];
}
public static void insertMore(ZeroStickyAdvertistmentAdapter sd, int howmany) {
for (int i = 0; i < howmany; i++) {
sd.insertFirst("More items " + i);
}
}
public static final Integer[] res = new Integer[]{
R.drawable.jr13,
R.drawable.jr16,
R.drawable.jr14,
R.drawable.jr15,
R.drawable.jr17,
R.drawable.jr1,
R.drawable.jr2,
R.drawable.jr3,
R.drawable.jr4,
R.drawable.jr5
};
public static final Integer[] res_scn = new Integer[]{
R.drawable.scn1,
R.drawable.scn2
};
public static final String[] girl_name = new String[]{
"Anna",
"Sindy",
"Venus",
"Pamela",
"Chantel",
"Lostus",
"Sephia",
"Sophy",
"YahoLee",
"Liza",
"Angel",
"Cristy",
"Gobby",
"Sophia",
"Nicole",
"Emily",
"Tiffany",
"Susan",
"Vicki",
"Eva",
"Ruby",
"Toby",
"Gobia",
"Victoria",
"Annus",
"Sammus",
"Sindia",
"Erica",
"Vivian",
"Septhanie",
"Fiona",
"Leonia",
"Karon"
};
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/TimeLineModel.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
/**
* Created by zJJ on 4/27/2016.
*/
public class TimeLineModel {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/modules/ViewPagerAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.modules;
import androidx.viewpager.widget.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.demo.R;
class ViewPagerAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.primaryContentCardView;
break;
case 1:
resId = R.id.secondaryContentFrameLayout;
break;
}
return collection.findViewById(resId);
}
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/multiitemdemo/MultiViewTypesActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.multiitemdemo;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.ui.divideritemdecoration.HorizontalDividerItemDecoration;
import java.util.ArrayList;
import java.util.List;
/**
* A activity which can be swiped to show bottom view with default horizontal divider item decoration.
*/
public class MultiViewTypesActivity extends AppCompatActivity {
UltimateRecyclerView ultimateRecyclerView;
MultiViewTypesRecyclerViewAdapter simpleRecyclerViewAdapter = null;
LinearLayoutManager linearLayoutManager;
int moreNum = 100;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadmore);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
List stringList = new ArrayList<>();
stringList.add("111");
stringList.add("aaa");
stringList.add("222");
stringList.add("33");
stringList.add("44");
stringList.add("55");
simpleRecyclerViewAdapter = new MultiViewTypesRecyclerViewAdapter(stringList);
simpleRecyclerViewAdapter.setCustomLoadMoreView(
LayoutInflater.from(this).inflate(R.layout.custom_bottom_progressbar, null));
// stringList.add("66");
// stringList.add("11771");
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
// ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
simpleRecyclerViewAdapter.insert("Refresh things", 0);
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
}
}, 1000);
}
});
Paint paint = new Paint();
paint.setStrokeWidth(5);
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setPathEffect(new DashPathEffect(new float[]{25.0f, 25.0f}, 0));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
ultimateRecyclerView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
ultimateRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).paint(paint).build());
// simpleRecyclerViewAdapter.ad
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/multiitemdemo/MultiViewTypesRecyclerViewAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.multiitemdemo;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.marshalchen.ultimaterecyclerview.UltimateDifferentViewTypeAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import java.util.ArrayList;
import java.util.List;
public class MultiViewTypesRecyclerViewAdapter extends UltimateDifferentViewTypeAdapter {
private List mDataset;
private enum SwipedState {
SHOWING_PRIMARY_CONTENT,
SHOWING_SECONDARY_CONTENT
}
private List mItemSwipedStates;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends UltimateRecyclerviewViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MultiViewTypesRecyclerViewAdapter(List dataSet) {
mDataset = dataSet;
mItemSwipedStates = new ArrayList<>();
for (int i = 0; i < dataSet.size(); i++) {
mItemSwipedStates.add(i, SwipedState.SHOWING_PRIMARY_CONTENT);
}
putBinder(SampleViewType.SAMPLE1, new Sample1Binder(this, dataSet));
putBinder(SampleViewType.SAMPLE2, new Sample2Binder(this, dataSet));
putBinder(SampleViewType.SAMPLE3, new Sample1Binder(this, dataSet));
// ((Sample2Binder) getDataBinder(SampleViewType.SAMPLE2)).addAll(dataSet);
}
public void insert(String string, int position) {
insertInternal(mDataset, string, position);
}
public void remove(int position) {
removeInternal(mDataset, position);
}
/**
* requirement: FOOTER, HEADER. it does not bind and need to do that in the header binding
*
* @param view with no binding view of nothing
* @return v
*/
@Override
public RecyclerView.ViewHolder newFooterHolder(View view) {
return new UltimateRecyclerviewViewHolder<>(view);
}
@Override
public RecyclerView.ViewHolder newHeaderHolder(View view) {
return new UltimateRecyclerviewViewHolder<>(view);
}
@Override
public UltimateRecyclerviewViewHolder onCreateViewHolder(ViewGroup parent) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_item_linear, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
return null;
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
}
// @Override
// public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//
// }
/**
* Called by RecyclerView to display the data at the specified position. This method should
* update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
* position.
*
* Note that unlike {@link ListView}, RecyclerView will not call this method
* again if the position of the item changes in the data set unless the item itself is
* invalidated or the new position cannot be determined. For this reason, you should only
* use the position parameter while acquiring the related data item inside
* this method and should not keep a copy of it. If you need the position of an item later
* on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
* have the updated adapter position.
*
* Override {@link #onBindViewHolder} instead if Adapter can
* handle effcient partial bind.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.size();
}
@Override
public int getAdapterItemCount() {
return 0;
}
@Override
public long generateHeaderId(int position) {
return 0;
}
@Override
public Enum getEnumFromPosition(int position) {
if (position % 2 == 1) {
return SampleViewType.SAMPLE1;
} else {
return SampleViewType.SAMPLE2;
}
}
@Override
public Enum getEnumFromOrdinal(int ordinal) {
return SampleViewType.values()[ordinal];
}
enum SampleViewType {
SAMPLE1, SAMPLE2, SAMPLE3
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/multiitemdemo/Sample1Binder.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.multiitemdemo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateDifferentViewTypeAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.multiViewTypes.DataBinder;
import java.util.List;
/**
* Created by cym on 15/5/18.
*/
public class Sample1Binder extends DataBinder {
List dataSet;
public Sample1Binder(UltimateDifferentViewTypeAdapter dataBindAdapter,List dataSet) {
super(dataBindAdapter);
this.dataSet=dataSet;
}
@Override
public ViewHolder newViewHolder(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.rv_sample_1, parent, false);
return new ViewHolder(view);
}
@Override
public void bindViewHolder(ViewHolder holder, int position) {
holder.mTitleText.setText("Sample1Binder "+dataSet.get(position));
}
@Override
public int getItemCount() {
return 1;
}
static class ViewHolder extends UltimateRecyclerviewViewHolder {
TextView mTitleText;
ImageView mImageView;
TextView mContent;
public ViewHolder(View view) {
super(view);
mTitleText = (TextView) view.findViewById(R.id.title_type1);
mImageView = (ImageView) view.findViewById(R.id.image_type1);
mContent = (TextView) view.findViewById(R.id.content_type1);
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/multiitemdemo/Sample2Binder.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.multiitemdemo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateDifferentViewTypeAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.multiViewTypes.DataBinder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cym on 15/5/18.
*/
public class Sample2Binder extends DataBinder {
private List mList;
public Sample2Binder(UltimateDifferentViewTypeAdapter dataBindAdapter,List mList) {
super(dataBindAdapter);
this.mList=mList;
}
@Override
public ViewHolder newViewHolder(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.rv_item_linear, parent, false);
return new ViewHolder(view);
}
@Override
public void bindViewHolder(ViewHolder holder, int position) {
holder.mTitleText.setText("Sample type 2 "+mList.get(position));
}
@Override
public int getItemCount() {
return 1;
}
static class ViewHolder extends UltimateRecyclerviewViewHolder {
TextView mTitleText;
ImageView mImageView;
TextView mContent;
public ViewHolder(View view) {
super(view);
mTitleText = (TextView) view.findViewById(R.id.textview);
mImageView = (ImageView) view.findViewById(R.id.imageview);
}
}
private List mDataSet = new ArrayList<>();
public void addAll(List dataSet) {
mDataSet.addAll(dataSet);
notifyBinderDataSetChanged();
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/SimpleAnimationAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.animation.Animator;
import android.graphics.Color;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.marshalchen.ultimaterecyclerview.demo.R;
import java.security.SecureRandom;
import java.util.List;
import jp.wasabeef.recyclerview.internal.ViewHelper;
public class SimpleAnimationAdapter extends UltimateViewAdapter {
private List stringList;
public SimpleAnimationAdapter(List stringList) {
this.stringList = stringList;
}
private int mDuration = 300;
private Interpolator mInterpolator = new LinearInterpolator();
private int mLastPosition = 5;
private boolean isFirstOnly = true;
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (position < getItemCount() && (customHeaderView != null ? position <= stringList.size() : position < stringList.size()) && (customHeaderView != null ? position > 0 : true)) {
((ViewHolder) holder).textViewSample.setText(stringList.get(customHeaderView != null ? position - 1 : position));
// ((ViewHolder) holder).itemView.setActivated(selectedItems.get(position, false));
}
if (!isFirstOnly || position > mLastPosition) {
for (Animator anim : getAdapterAnimations(holder.itemView, AdapterAnimationType.ScaleIn)) {
anim.setDuration(mDuration).start();
anim.setInterpolator(mInterpolator);
}
mLastPosition = position;
} else {
ViewHelper.clear(holder.itemView);
}
}
@Override
public int getAdapterItemCount() {
return stringList.size();
}
/**
* requirement: FOOTER, HEADER. it does not bind and need to do that in the header binding
*
* @param view with no binding view of nothing
* @return v
*/
@Override
public RecyclerView.ViewHolder newFooterHolder(View view) {
return new ViewHolder(view, false);
}
@Override
public RecyclerView.ViewHolder newHeaderHolder(View view) {
return new ViewHolder(view, false);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_item_linear, parent, false);
return new ViewHolder(v, true);
}
public void insert(String string, int position) {
insertInternal(stringList, string, position);
}
public void remove(int position) {
removeInternal(stringList, position);
}
public void clear() {
clearInternal(stringList);
}
public void swapPositions(int from, int to) {
swapPositions(stringList, from, to);
}
@Override
public long generateHeaderId(int position) {
URLogs.d("position--" + position + " " + getItem(position));
if (getItem(position).length() > 0)
return getItem(position).charAt(0);
else return -1;
}
@Override
public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.stick_header_item, viewGroup, false);
return new ViewHolder(view, false);
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.stick_text);
textView.setText(String.valueOf(getItem(position).charAt(0)));
// viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
viewHolder.itemView.setBackgroundColor(Color.parseColor("#AAffffff"));
ImageView imageView = (ImageView) viewHolder.itemView.findViewById(R.id.stick_img);
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
imageView.setImageResource(R.drawable.scn1);
break;
case 1:
imageView.setImageResource(R.drawable.jr13);
break;
case 2:
imageView.setImageResource(R.drawable.jr16);
break;
}
}
//
// private int getRandomColor() {
// SecureRandom rgen = new SecureRandom();
// return Color.HSVToColor(150, new float[]{
// rgen.nextInt(359), 1, 1
// });
// }
public class ViewHolder extends UltimateRecyclerviewViewHolder {
public TextView textViewSample;
public ImageView imageViewSample;
public ViewHolder(View itemView, boolean normal) {
super(itemView);
// itemView.setOnTouchListener(new SwipeDismissTouchListener(itemView, null, new SwipeDismissTouchListener.DismissCallbacks() {
// @Override
// public boolean canDismiss(Object token) {
// Logs.d("can dismiss");
// return true;
// }
//
// @Override
// public void onDismiss(View view, Object token) {
// // Logs.d("dismiss");
// remove(getPosition());
//
// }
// }));
if (normal) {
textViewSample = (TextView) itemView.findViewById(
R.id.textview);
imageViewSample = (ImageView) itemView.findViewById(R.id.imageview);
}
}
}
public String getItem(int position) {
if (customHeaderView != null)
position--;
if (position < stringList.size())
return stringList.get(position);
else return "";
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/SwipeAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.marshalchen.ultimaterecyclerview.SwipeableUltimateViewAdapter;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.swipe.SwipeLayout;
import java.util.List;
public class SwipeAdapter extends SwipeableUltimateViewAdapter {
public SwipeAdapter(List mData) {
super(mData);
}
@Override
protected void withBindHolder(UltimateRecyclerviewViewHolder holder, String data, int position) {
super.withBindHolder(holder, data, position);
((SVHolder) holder).textView.setText(data);
}
/**
* the layout id for the normal data
*
* @return the ID
*/
@Override
protected int getNormalLayoutResId() {
return SVHolder.layout;
}
/**
* this is the Normal View Holder initiation
*
* @param view view
* @return holder
*/
@Override
protected UltimateRecyclerviewViewHolder newViewHolder(final View view) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
URLogs.d("click");
}
});
final SVHolder viewHolder = new SVHolder(view, true);
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
@Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(view.getContext(), "DoubleClick", Toast.LENGTH_SHORT).show();
}
});
viewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
removeAt(viewHolder.getPosition());
Toast.makeText(view.getContext(), "Deleted " + viewHolder.getPosition(), Toast.LENGTH_SHORT).show();
}
});
return viewHolder;
}
@Override
public SVHolder newFooterHolder(View view) {
return new SVHolder(view, false);
}
@Override
public SVHolder newHeaderHolder(View view) {
return new SVHolder(view, false);
}
@Override
public long generateHeaderId(int position) {
return 0;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
protected void removeNotifyExternal(int pos) {
closeItem(pos);
}
public static class SVHolder extends UltimateRecyclerviewViewHolder {
public static final int layout = R.layout.item_swipeable;
public TextView textView;
public Button deleteButton;
public SwipeLayout swipeLayout;
public SVHolder(View itemView, boolean bind) {
super(itemView);
if (bind) {
textView = (TextView) itemView.findViewById(R.id.position);
deleteButton = (Button) itemView.findViewById(R.id.delete);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.recyclerview_swipe);
swipeLayout.setDragEdge(SwipeLayout.DragEdge.Right);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/TimeLineAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.demo.modules.TimeLineModel;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import com.marshalchen.ultimaterecyclerview.ui.timelineview.TimelineView;
import java.util.List;
/**
* Created by zJJ on 4/27/2016.
*/
public class TimeLineAdapter extends easyRegularAdapter {
public TimeLineAdapter(List feedList) {
super(feedList);
}
@Override
protected int getNormalLayoutResId() {
return itemNode.layout;
}
@Override
protected itemNode newViewHolder(View view) {
return new itemNode(view);
}
@Override
protected void withBindHolder(itemNode holder, TimeLineModel data, int position) {
holder.name.setText("name:" + data.getName() + " age:" + data.getAge());
holder.init(TimelineView.getTimeLineViewType(position, getItemCount()));
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/itemCommonBinder.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
/**
* Created by hesk on 16/2/16.
* this is the example holder for the simple adapter
*/
public class itemCommonBinder extends UltimateRecyclerviewViewHolder {
public static final int layout = R.layout.rv_item_linear;
public TextView textViewSample;
public ImageView imageViewSample;
public ProgressBar progressBarSample;
public RelativeLayout item_view;
/**
* give more control over NORMAL or HEADER view binding
*
* @param itemView view binding
* @param isItem bool
*/
public itemCommonBinder(View itemView, boolean isItem) {
super(itemView);
// itemView.setOnTouchListener(new SwipeDismissTouchListener(itemView, null, new SwipeDismissTouchListener.DismissCallbacks() {
// @Override
// public boolean canDismiss(Object token) {
// Logs.d("can dismiss");
// return true;
// }
//
// @Override
// public void onDismiss(View view, Object token) {
// // Logs.d("dismiss");
// remove(getPosition());
//
// }
// }));
if (isItem) {
textViewSample = (TextView) itemView.findViewById(R.id.str_textview_holder);
imageViewSample = (ImageView) itemView.findViewById(R.id.str_image_holder);
progressBarSample = (ProgressBar) itemView.findViewById(R.id.str_progress_holder);
item_view = (RelativeLayout) itemView.findViewById(R.id.str_item_view);
}
}
@Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
@Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/itemGridCellBinder.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
/**
* Created by hesk on 3/2/16.
*/
public class itemGridCellBinder extends UltimateRecyclerviewViewHolder {
public static final int layout = R.layout.grid_item;
public TextView textViewSample;
public ImageView imageViewSample;
public View item_view;
public itemGridCellBinder(View itemView, boolean isItem) {
super(itemView);
if (isItem) {
textViewSample = (TextView) itemView.findViewById(R.id.example_row_tv_title);
imageViewSample = (ImageView) itemView.findViewById(R.id.example_row_iv_image);
item_view = itemView.findViewById(R.id.planview);
}
}
@Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
@Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/itemNode.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.view.View;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.ui.timelineview.TimelineView;
/**
* Created by zJJ on 4/27/2016.
*/
public class itemNode extends UltimateRecyclerviewViewHolder {
public static final int layout = R.layout.item_node;
public TimelineView mTimelineView;
public TextView name;
/**
* the view
*
* @param itemView the view context
*/
public itemNode(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tx_name);
mTimelineView = (TimelineView) itemView.findViewById(R.id.time_marker);
}
/**
* this is the initialization of the node
*
* @param viewTypeLine the type of node to redraw
*/
public void init(int viewTypeLine) {
mTimelineView.initLine(viewTypeLine);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/itemStaggerCommonBinder.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.quickAdapter.StaggerHolder;
/**
* Created by hesk on 5/4/16.
*/
public class itemStaggerCommonBinder extends StaggerHolder {
public static final int layout = R.layout.rv_item_stagger;
public TextView textViewSample;
public ImageView imageViewSample;
public ProgressBar progressBarSample;
public RelativeLayout item_view;
public itemStaggerCommonBinder(View itemView, int type) {
super(itemView, type);
}
@Override
protected void bindHeader(View view) {
}
@Override
protected void bindFooter(View view) {
}
@Override
protected void bindNormal(View view) {
textViewSample = (TextView) itemView.findViewById(R.id.str_textview_holder);
imageViewSample = (ImageView) itemView.findViewById(R.id.str_image_holder);
progressBarSample = (ProgressBar) itemView.findViewById(R.id.str_progress_holder);
item_view = (RelativeLayout) itemView.findViewById(R.id.str_item_view);
}
@Override
protected void bindAd(View view) {
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/sectionCommonAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.graphics.Color;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import java.security.SecureRandom;
import java.util.List;
/**
* Created by hesk on 16/2/16.
*/
public class sectionCommonAdapter extends easyRegularAdapter {
/**
* dynamic object to start
*
* @param list the list source
*/
public sectionCommonAdapter(List list) {
super(list);
}
/**
* the layout id for the normal data
*
* @return the ID
*/
@Override
protected int getNormalLayoutResId() {
return itemCommonBinder.layout;
}
@Override
protected itemCommonBinder newViewHolder(View view) {
return new itemCommonBinder(view, true);
}
private void setRandomImage(ImageView image) {
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
image.setImageResource(R.drawable.scn1);
break;
case 1:
image.setImageResource(R.drawable.jr13);
break;
case 2:
image.setImageResource(R.drawable.jr16);
break;
}
}
@Override
protected void withBindHolder(itemCommonBinder holder, String data, int position) {
char Firstletter = data.charAt(0);
holder.textViewSample.setText(data);
holder.item_view.setBackgroundColor(Color.parseColor("#AAffffff"));
setRandomImage(holder.imageViewSample);
/* if (position < getItemCount() && (hasHeaderView() ? position <= getAdapterItemCount() : position < getAdapterItemCount()) && (hasHeaderView() ? position > 0 : true)) {
holder.textViewSample.setText(getItem(hasHeaderView() ? position - 1 : position));
if (mDragStartListener != null) {
holder.item_view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
}
}*/
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
swapPositions(fromPosition, toPosition);
// notifyItemMoved(fromPosition, toPosition);
super.onItemMove(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
if (position > 0)
removeAt(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();
super.onItemDismiss(position);
}
public void setOnDragStartListener(OnStartDragListener dragStartListener) {
mDragStartListener = dragStartListener;
}
/**
* this is the way to enable section header
*
* @param i position in the display items
* @return long position
*/
@Override
public long generateHeaderId(int i) {
if (getItem(i).length() > 0) {
return getItem(i).charAt(0);
} else return -1;
}
/**
* this is the way to enable section header
*
* @param viewGroup enable the view group
* @return view holder
*/
@Override
public UltimateRecyclerviewViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.stick_header_item, viewGroup, false);
return new UltimateRecyclerviewViewHolder(view) {
};
}
/**
* this is the section header binding
*
* @param viewHolder section holder
* @param position position
*/
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.stick_text);
textView.setText(String.valueOf(getItem(hasHeaderView() ? position - 1 : position).charAt(0)));
// viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
viewHolder.itemView.setBackgroundColor(Color.parseColor("#AAffffff"));
ImageView imageView = (ImageView) viewHolder.itemView.findViewById(R.id.stick_img);
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
imageView.setImageResource(R.drawable.scn1);
break;
case 1:
imageView.setImageResource(R.drawable.jr13);
break;
case 2:
imageView.setImageResource(R.drawable.jr16);
break;
}
}
@Override
public itemCommonBinder newFooterHolder(View view) {
return new itemCommonBinder(view, false);
}
@Override
public itemCommonBinder newHeaderHolder(View view) {
return new itemCommonBinder(view, false);
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/sectionZeroAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.graphics.Color;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import java.security.SecureRandom;
import java.util.List;
public class sectionZeroAdapter extends easyRegularAdapter {
// private List stringList;
public sectionZeroAdapter(List stringList) {
super(stringList);
// this.stringList = stringList;
}
/**
* the layout id for the normal data
*
* @return the ID
*/
@Override
protected int getNormalLayoutResId() {
return itemCommonBinder.layout;
}
@Override
protected itemCommonBinder newViewHolder(View view) {
return new itemCommonBinder(view, true);
}
@Override
public itemCommonBinder newFooterHolder(View view) {
return new itemCommonBinder(view, false);
}
@Override
public itemCommonBinder newHeaderHolder(View view) {
return new itemCommonBinder(view, false);
}
/* @Override
public void onBindViewHolder(final SHol holder, int position) {
if (position < getItemCount() && (customHeaderView != null ? position <= stringList.size() : position < stringList.size()) && (customHeaderView != null ? position > 0 : true)) {
((SHol) holder).textViewSample.setText(stringList.get(customHeaderView != null ? position - 1 : position));
// ((ViewHolder) holder).itemView.setActivated(selectedItems.get(position, false));
if (mDragStartListener != null) {
// ((ViewHolder) holder).imageViewSample.setOnTouchListener(new View.OnTouchListener() {
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
// mDragStartListener.onStartDrag(holder);
// }
// return false;
// }
// });
((SHol) holder).item_view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
}
}
}
*/
public final void insertOne(String e) {
insertLast(e);
}
public final void removeLastOne() {
removeLast();
}
/*
@Override
public long generateHeaderId(int position) {
// URLogs.d("position--" + position + " " + getItem(position));
if (getItem(position).length() > 0)
return getItem(position).charAt(0);
else return -1;
}*/
@Override
protected void withBindHolder(itemCommonBinder holder, String data, int position) {
holder.textViewSample.setText(data + "just the sample data");
holder.item_view.setBackgroundColor(Color.parseColor("#AAffffff"));
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
holder.imageViewSample.setImageResource(R.drawable.scn1);
break;
case 1:
holder.imageViewSample.setImageResource(R.drawable.jr13);
break;
case 2:
holder.imageViewSample.setImageResource(R.drawable.jr16);
break;
}
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
swapPositions(fromPosition, toPosition);
// notifyItemMoved(fromPosition, toPosition);
super.onItemMove(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
if (position > 0)
removeAt(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();
super.onItemDismiss(position);
}
/* public String getItem(int position) {
if (customHeaderView != null)
position--;
if (position < stringList.size())
return stringList.get(position);
else
return "";
}*/
//
// private int getRandomColor() {
// SecureRandom rgen = new SecureRandom();
// return Color.HSVToColor(150, new float[]{
// rgen.nextInt(359), 1, 1
// });
// }
public void setOnDragStartListener(OnStartDragListener dragStartListener) {
mDragStartListener = dragStartListener;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/rvComponents/staggerAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.rvComponents;
import android.graphics.Color;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import java.security.SecureRandom;
import java.util.List;
/**
* Created by hesk on 5/4/16.
*/
public class staggerAdapter extends easyRegularAdapter {
public staggerAdapter(List stringList) {
super(stringList);
// this.stringList = stringList;
}
@Override
protected int getNormalLayoutResId() {
return itemStaggerCommonBinder.layout;
}
@Override
protected itemStaggerCommonBinder newViewHolder(View view) {
return new itemStaggerCommonBinder(view, VIEW_TYPES.NORMAL);
}
@Override
public itemStaggerCommonBinder newFooterHolder(View view) {
return new itemStaggerCommonBinder(view, VIEW_TYPES.FOOTER);
}
@Override
public itemStaggerCommonBinder newHeaderHolder(View view) {
return new itemStaggerCommonBinder(view, VIEW_TYPES.HEADER);
}
@Override
protected void withBindHolder(itemStaggerCommonBinder holder, String data, int position) {
holder.textViewSample.setText(data + "just the sample data");
holder.item_view.setBackgroundColor(Color.parseColor("#AAffffff"));
SecureRandom imgGen = new SecureRandom();
switch (imgGen.nextInt(3)) {
case 0:
holder.imageViewSample.setImageResource(R.drawable.scn1);
break;
case 1:
holder.imageViewSample.setImageResource(R.drawable.jr13);
break;
case 2:
holder.imageViewSample.setImageResource(R.drawable.jr16);
break;
}
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
swapPositions(fromPosition, toPosition);
// notifyItemMoved(fromPosition, toPosition);
super.onItemMove(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
if (position > 0)
removeAt(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();
super.onItemDismiss(position);
}
public void setOnDragStartListener(OnStartDragListener dragStartListener) {
mDragStartListener = dragStartListener;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/BaseActivity.java
================================================
/*
* Copyright 2014 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable;
import android.content.res.TypedArray;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import java.util.ArrayList;
public abstract class BaseActivity extends AppCompatActivity {
private static final int NUM_OF_ITEMS = 100;
private static final int NUM_OF_ITEMS_FEW = 3;
protected int getActionBarSize() {
TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[]{R.attr.actionBarSize};
int indexOfAttrTextSize = 0;
TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr);
int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
return actionBarSize;
}
protected int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
public static ArrayList getDummyData() {
return getDummyData(NUM_OF_ITEMS);
}
public static ArrayList getDummyData(int num) {
ArrayList items = new ArrayList<>();
for (int i = 1; i <= num; i++) {
items.add("Item " + i);
}
return items;
}
protected void setDummyData(ListView listView) {
setDummyData(listView, NUM_OF_ITEMS);
}
protected void setDummyDataFew(ListView listView) {
setDummyData(listView, NUM_OF_ITEMS_FEW);
}
protected void setDummyData(ListView listView, int num) {
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getDummyData(num)));
}
protected void setDummyDataWithHeader(ListView listView, int headerHeight) {
setDummyDataWithHeader(listView, headerHeight, NUM_OF_ITEMS);
}
protected void setDummyDataWithHeader(ListView listView, int headerHeight, int num) {
View headerView = new View(this);
headerView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, headerHeight));
headerView.setMinimumHeight(headerHeight);
// This is required to disable header's list selector effect
headerView.setClickable(true);
setDummyDataWithHeader(listView, headerView, num);
}
protected void setDummyDataWithHeader(ListView listView, View headerView, int num) {
listView.addHeaderView(headerView);
setDummyData(listView, num);
}
/*
protected void setDummyData(GridView gridView) {
gridView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getDummyData()));
}
protected void setDummyData(RecyclerView recyclerView) {
setDummyData(recyclerView, NUM_OF_ITEMS);
}
protected void setDummyDataFew(RecyclerView recyclerView) {
setDummyData(recyclerView, NUM_OF_ITEMS_FEW);
}*/
protected void setDummyData(RecyclerView recyclerView, int num) {
recyclerView.setAdapter(new sectionZeroAdapter(getDummyData(num)));
}
protected void setDummyData(RecyclerView recyclerView) {
setDummyData(recyclerView, NUM_OF_ITEMS);
}
/*
protected void setDummyDataWithHeader(RecyclerView recyclerView, int headerHeight) {
View headerView = new View(this);
headerView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, headerHeight));
headerView.setMinimumHeight(headerHeight);
// This is required to disable header's list selector effect
headerView.setClickable(true);
// setDummyDataWithHeader(recyclerView, headerView);
}
protected void setDummyDataWithHeader(RecyclerView recyclerView, View headerView) {
recyclerView.setAdapter(new SimpleAdapter(this, getDummyData(), headerView));
}*/
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/BaseFragment.java
================================================
/*
* Copyright 2014 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable;
import android.app.Activity;
import android.content.res.TypedArray;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import java.util.ArrayList;
public abstract class BaseFragment extends Fragment {
public static ArrayList getDummyData() {
return BaseActivity.getDummyData();
}
protected int getActionBarSize() {
Activity activity = getActivity();
if (activity == null) {
return 0;
}
TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[]{R.attr.actionBarSize};
int indexOfAttrTextSize = 0;
TypedArray a = activity.obtainStyledAttributes(typedValue.data, textSizeAttr);
int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
return actionBarSize;
}
protected int getScreenHeight() {
Activity activity = getActivity();
if (activity == null) {
return 0;
}
return activity.findViewById(android.R.id.content).getHeight();
}
protected void setDummyData(ListView listView) {
listView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, getDummyData()));
}
protected void setDummyDataWithHeader(ListView listView, View headerView) {
listView.addHeaderView(headerView);
setDummyData(listView);
}
protected void setDummyData(GridView gridView) {
gridView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, getDummyData()));
}
protected void setDummyData(RecyclerView recyclerView) {
recyclerView.setAdapter(new sectionZeroAdapter(getDummyData()));
}
protected void setDummyData(UltimateRecyclerView recyclerView) {
recyclerView.setAdapter(new sectionZeroAdapter(getDummyData()));
}
/* protected void setDummyDataWithHeader(RecyclerView recyclerView, View headerView) {
recyclerView.setAdapter(new SimpleHeaderRecyclerAdapter(getActivity(), getDummyData(), headerView));
}*/
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/ScrollObservablesActivity.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable;
import android.os.Bundle;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.marshalchen.ultimaterecyclerview.demo.R;
/**
* Created by hesk on 12/6/15.
*/
public class ScrollObservablesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_scroll_activity);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag(ViewPagerTabFragmentParentFragment.FRAGMENT_TAG) == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment, new ViewPagerTabFragmentParentFragment(),
ViewPagerTabFragmentParentFragment.FRAGMENT_TAG);
ft.commit();
fm.executePendingTransactions();
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/ViewPagerFragmentListSingle.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.ObservableScrollViewCallbacks;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
/**
* Created by hesk on 12/6/15.
*/
public class ViewPagerFragmentListSingle extends BaseFragment {
protected ObservableScrollViewCallbacks parent_fragment;
public static String TAG = "thisWork";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.listurv, container, false);
final UltimateRecyclerView recyclerView = (UltimateRecyclerView) view.findViewById(R.id.scroll);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(false);
recyclerView.setRefreshing(false);
setDummyData(recyclerView);
ViewPagerTabFragmentParentFragment parentFragment = (ViewPagerTabFragmentParentFragment) getParentFragment();
ViewGroup parentFView = (ViewGroup) parentFragment.getView();
if (parentFragment != null) {
recyclerView.setTouchInterceptionViewGroup((ViewGroup) parentFView.findViewById(R.id.container));
if (parentFragment instanceof ObservableScrollViewCallbacks) {
recyclerView.setScrollViewCallbacks(parentFragment);
Log.d(TAG, "this is ObservableScrollViewCallbacks");
}
}
return view;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/ViewPagerTabFragmentParentFragment.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable;
import android.animation.ValueAnimator;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.core.view.ViewCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.marshalchen.ultimaterecyclerview.ObservableScrollState;
import com.marshalchen.ultimaterecyclerview.ObservableScrollViewCallbacks;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.uiUtils.ScrollUtils;
import com.marshalchen.ultimaterecyclerview.Scrollable;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.scrollableobservable.widget.SlidingTabLayout;
import com.marshalchen.ultimaterecyclerview.uiUtils.CacheFragmentStatePagerAdapter;
import com.marshalchen.ultimaterecyclerview.uiUtils.TouchInterceptionLayout;
/**
* Created by hesk on 12/6/15.
*/
public class ViewPagerTabFragmentParentFragment extends BaseFragment implements ObservableScrollViewCallbacks {
public static final String FRAGMENT_TAG = "fragmentViewPager";
private TouchInterceptionLayout mInterceptionLayout;
private ViewPager mPager;
private NavigationAdapter mPagerAdapter;
private int mSlop;
private boolean mScrolled = false;
private ObservableScrollState mLastScrollState;
private View mHeaderContainer;
private ImageView headerBanner;
private int slidingTabLayout_height, mBaseTranslationY;
private SlidingTabLayout slidingTabLayout;
private FrameLayout pager_wrapper;
private int totalfullheight;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.simplefragment_viewpaper_fragment_parent, container, false);
totalfullheight = view.getHeight();
AppCompatActivity parentActivity = (AppCompatActivity) getActivity();
mPagerAdapter = new NavigationAdapter(getChildFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.pager);
pager_wrapper = (FrameLayout) view.findViewById(R.id.pager_wrapper);
mPager.setAdapter(mPagerAdapter);
mHeaderContainer = (View) view.findViewById(R.id.header);
headerBanner = (ImageView) view.findViewById(R.id.header_background);
slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
slidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
slidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.accent));
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(mPager);
ViewConfiguration vc = ViewConfiguration.get(parentActivity);
mSlop = vc.getScaledTouchSlop();
mInterceptionLayout = (TouchInterceptionLayout) view.findViewById(R.id.container);
mInterceptionLayout.setScrollInterceptionListener(mInterceptionListener);
mPager.setCurrentItem(0);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
setpagertoppadding(headerBanner.getHeight() + slidingTabLayout.getHeight());
}
protected void setpagertoppadding(float m) {
final int mheight = (int) Math.abs(m);
pager_wrapper.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mheight));
pager_wrapper.requestLayout();
}
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if (dragging) {
int headerBannerHeight = headerBanner.getHeight();
float currentHeaderTranslationY = ViewCompat.getTranslationY(mHeaderContainer);
if (firstScroll) {
if (-headerBannerHeight < currentHeaderTranslationY) {
mBaseTranslationY = scrollY;
}
}
final float headerTranslationY = ScrollUtils.getFloat(mBaseTranslationY - scrollY, -headerBannerHeight, 0);
ViewCompat.animate(mHeaderContainer).cancel();
ViewCompat.setTranslationY(mHeaderContainer, headerTranslationY);
//todo: need some more works on this
setpagertoppadding(totalfullheight - headerTranslationY);
}
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(final ObservableScrollState scrollState) {
if (!mScrolled) {
// This event can be used only when TouchInterceptionFrameLayout
// doesn't handle the consecutive events.
// toolbarAdjustment(scrollState);
mBaseTranslationY = 0;
final Fragment fragment = getCurrentFragment();
if (fragment == null) {
return;
}
View view = fragment.getView();
if (view == null) {
return;
}
// toolbarAdjustment(mLastScrollState, view);
}
}
private TouchInterceptionLayout.TouchInterceptionListener mInterceptionListener = new TouchInterceptionLayout.TouchInterceptionListener() {
@Override
public boolean shouldInterceptTouchEvent(MotionEvent ev, boolean moving, float diffX, float diffY) {
if (!mScrolled && mSlop < Math.abs(diffX) && Math.abs(diffY) < Math.abs(diffX)) {
// Horizontal scroll is maybe handled by ViewPager
return false;
}
Scrollable scrollable = getCurrentScrollable();
if (scrollable == null) {
mScrolled = false;
return false;
}
// If interceptionLayout can move, it should intercept.
// And once it begins to move, horizontal scroll shouldn't work any longer.
// View toolbarView = getActivity().findViewById(R.id.toolbar);
int headerBannerHeight = headerBanner.getHeight();
int translationY = (int) ViewCompat.getTranslationY(mInterceptionLayout);
boolean scrollingUp = 0 < diffY;
boolean scrollingDown = diffY < 0;
if (scrollingUp) {
if (translationY < 0) {
mScrolled = true;
mLastScrollState = ObservableScrollState.UP;
return true;
}
} else if (scrollingDown) {
if (-headerBannerHeight < translationY) {
mScrolled = true;
mLastScrollState = ObservableScrollState.DOWN;
return true;
}
}
mScrolled = false;
return false;
}
@Override
public void onDownMotionEvent(MotionEvent ev) {
}
@Override
public void onMoveMotionEvent(MotionEvent ev, float diffX, float diffY) {
/* View tView = adjustmentToolBarView();
float translationY = ScrollUtils.getFloat(ViewCompat.getTranslationY(mInterceptionLayout) + diffY, -tView.getHeight(), 0);
ViewCompat.setTranslationY(mInterceptionLayout, translationY);
ViewCompat.setTranslationY(tView, translationY);
if (translationY < 0) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mInterceptionLayout.getLayoutParams();
lp.height = (int) (-translationY + getScreenHeight());
mInterceptionLayout.requestLayout();
}*/
float translationY = ScrollUtils.getFloat(ViewCompat.getTranslationY(mInterceptionLayout) + diffY, -headerBanner.getHeight(), 0);
ViewCompat.setTranslationY(mInterceptionLayout, translationY);
if (translationY < 0) {
// start getting smaller
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mInterceptionLayout.getLayoutParams();
lp.height = (int) (-translationY + getScreenHeight());
mInterceptionLayout.requestLayout();
}
}
@Override
public void onUpOrCancelMotionEvent(MotionEvent ev) {
mScrolled = false;
// toolbarAdjustment(mLastScrollState);
}
};
private Scrollable getCurrentScrollable() {
Fragment fragment = getCurrentFragment();
if (fragment == null) {
return null;
}
View view = fragment.getView();
if (view == null) {
return null;
}
return viewscrollable(view);
}
private Scrollable viewscrollable(View fromFragmentView) {
return (Scrollable) fromFragmentView.findViewById(R.id.scroll);
}
private View adjustmentToolBarView() {
return getActivity().findViewById(R.id.toolbar);
// return getCurrentFragment().getView().findViewById(R.id.header);
}
private void toolbarAdjustment(ObservableScrollState scrollState) {
View tView = adjustmentToolBarView();
int toolbarHeight = tView.getHeight();
final Scrollable scrollable = getCurrentScrollable();
if (scrollable == null) {
return;
}
int scrollY = scrollable.getCurrentScrollY();
if (scrollState == ObservableScrollState.DOWN) {
showToolbar();
} else if (scrollState == ObservableScrollState.UP) {
if (toolbarHeight <= scrollY) {
hideToolbar();
} else {
showToolbar();
}
} else if (!toolbarIsShown() && !toolbarIsHidden()) {
// Toolbar is moving but doesn't know which to move:
// you can change this to hideToolbar()
showToolbar();
}
}
private void toolbarAdjustment(ObservableScrollState scrollState, View view) {
int toolbarHeight = headerBanner.getHeight();
final Scrollable scrollView = viewscrollable(view);
if (scrollView == null) {
return;
}
int scrollY = scrollView.getCurrentScrollY();
if (scrollState == ObservableScrollState.DOWN) {
showToolbar();
} else if (scrollState == ObservableScrollState.UP) {
if (toolbarHeight <= scrollY) {
hideToolbar();
} else {
showToolbar();
}
} else {
// Even if onScrollChanged occurs without scrollY changing, toolbar should be adjusted
if (toolbarIsShown() || toolbarIsHidden()) {
// Toolbar is completely moved, so just keep its state
// and propagate it to other pages
propagateToolbarState(toolbarIsShown());
} else {
// Toolbar is moving but doesn't know which to move:
// you can change this to hideToolbar()
showToolbar();
}
}
}
private void propagateToolbarState(boolean isShown) {
final int toolbarHeight = headerBanner.getHeight();
// Set scrollY for the fragments that are not created yet
mPagerAdapter.setScrollY(isShown ? 0 : toolbarHeight);
// Set scrollY for the active fragments
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
// Skip current item
if (i == mPager.getCurrentItem()) {
continue;
}
// Skip destroyed or not created item
Fragment f = mPagerAdapter.getItemAt(i);
if (f == null) {
continue;
}
View view = f.getView();
if (view == null) {
continue;
}
if (view.findViewById(R.id.scroll) instanceof UltimateRecyclerView) {
UltimateRecyclerView listView = (UltimateRecyclerView) viewscrollable(view);
if (isShown) {
// Scroll up
if (0 < listView.getCurrentScrollY()) {
// listView.setSelection(0);
Log.d(FRAGMENT_TAG, "up");
}
} else {
// Scroll down (to hide padding)
if (listView.getCurrentScrollY() < toolbarHeight) {
//listView.setSelection(1);
Log.d(FRAGMENT_TAG, "down");
}
}
}
}
}
private Fragment getCurrentFragment() {
return mPagerAdapter.getItemAt(mPager.getCurrentItem());
}
private boolean toolbarIsShown() {
return ViewCompat.getTranslationY(mInterceptionLayout) == 0;
}
private boolean toolbarIsHidden() {
View view = getView();
if (view == null) {
return false;
}
View tView = adjustmentToolBarView();
return ViewCompat.getTranslationY(mInterceptionLayout) == -tView.getHeight();
}
private void showToolbar() {
animateToolbar(0);
}
private void hideToolbar() {
View tView = adjustmentToolBarView();
animateToolbar(-tView.getHeight());
}
private void animateToolbar(final float toY) {
float layoutTranslationY = ViewCompat.getTranslationY(mInterceptionLayout);
if (layoutTranslationY != toY) {
ValueAnimator animator = ValueAnimator.ofFloat(ViewCompat.getTranslationY(mInterceptionLayout), toY).setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float translationY = (float) animation.getAnimatedValue();
View tView = adjustmentToolBarView();
ViewCompat.setTranslationY(mInterceptionLayout, translationY);
ViewCompat.setTranslationY(tView, translationY);
if (translationY < 0) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mInterceptionLayout.getLayoutParams();
lp.height = (int) (-translationY + getScreenHeight());
mInterceptionLayout.requestLayout();
}
}
});
animator.start();
}
}
/**
* This adapter provides two types of fragments as an example.
* {@linkplain #createItem(int)} should be modified if you use this example for your app.
*/
private static class NavigationAdapter extends CacheFragmentStatePagerAdapter {
private static final String[] TITLES = new String[]{"Applepie", "Butter Cookie", "Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "KitKat", "Lollipop"};
// private static final String[] TITLES = new String[]{"fff", "nd eee"};
public NavigationAdapter(FragmentManager fm) {
super(fm);
}
private int mScrollY;
public void setScrollY(int scrollY) {
mScrollY = scrollY;
}
@Override
protected Fragment createItem(int position) {
Fragment f = new ViewPagerFragmentListSingle();
if (0 < mScrollY) {
Bundle args = new Bundle();
// args.putInt(ViewPagerTab2RecyclerViewFragment.ARG_INITIAL_POSITION, 1);
f.setArguments(args);
}
return f;
/*
Fragment f;
final int pattern = position % 5;
switch (pattern) {
case 0:
f = new ViewPagerTab2RecyclerViewFragment();
break;
case 1:
f = new ViewPagerTab2RecyclerViewFragment();
break;
case 2:
f = new ViewPagerTab2RecyclerViewFragment();
break;
case 3:
f = new ViewPagerTab2RecyclerViewFragment();
break;
case 4:
default:
f = new ViewPagerTab2RecyclerViewFragment();
break;
}
return f;*/
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/widget/SlidingTabLayout.java
================================================
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* To be used with ViewPager to provide a tab indicator component which give constant feedback as to
* the user's scroll progress.
*
* To use the component, simply add it to your view hierarchy. Then in your
* {@link android.app.Activity} or {@link Fragment} call
* {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for.
*
* The colors can be customized in two ways. The first and simplest is to provide an array of colors
* via {@link #setSelectedIndicatorColors(int...)}. The
* alternative is via the {@link com.google.samples.apps.iosched.ui.widget.SlidingTabLayout.TabColorizer} interface which provides you complete control over
* which color is used for any individual position.
*
* The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)},
* providing the layout ID of your custom layout.
*/
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {@link #setCustomTabColorizer(com.google.samples.apps.iosched.ui.widget.SlidingTabLayout.TabColorizer)}.
*/
public interface TabColorizer {
/**
* @return return the color of the indicator used when {@code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray mContentDescriptions = new SparseArray();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {@link com.google.samples.apps.iosched.ui.widget.SlidingTabLayout.TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {@link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {@link ViewPager.OnPageChangeListener}. When using {@link com.google.samples.apps.iosched.ui.widget.SlidingTabLayout} you are
* required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* @param layoutResId Layout id to be inflated
* @param textViewId id of the {@link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {@link #setCustomTabView(int, int)}.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
}
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements OnClickListener {
@Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/scrollableobservable/widget/SlidingTabStrip.java
================================================
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.demo.scrollableobservable.widget;
import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
class SlidingTabStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
final int themeForegroundColor = outValue.data;
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
void setSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
void onViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {@code color} to be the given {@code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {@code color1} and {@code color2} using the given ratio.
*
* @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
* 0.0 will return {@code color2}.
*/
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
private int[] mIndicatorColors;
@Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/swiplistdemo/PackageAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.demo.swiplistdemo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.demo.R;
import java.util.List;
public class PackageAdapter extends RecyclerView.Adapter {
private List data;
private Context context;
public PackageAdapter(Context context, List data) {
this.context = context;
this.data = data;
}
public String getItem(int position) {
return data.get(position);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.package_row, viewGroup, false);
ViewHolder vh = new ViewHolder(itemView);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
final String item = getItem(i);
URLogs.d("" + viewHolder.ivImage);
viewHolder.tvTitle.setText(data.get(i));
//
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return data.size();
}
// @Override
// public View getView(final int position, View convertView, ViewGroup parent) {
// final PackageItem item = getItem(position);
// ViewHolder holder;
// if (convertView == null) {
// LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = li.inflate(R.layout.package_row, parent, false);
// holder = new ViewHolder();
// holder.ivImage = (ImageView) convertView.findViewById(R.id.example_row_iv_image);
// holder.tvTitle = (TextView) convertView.findViewById(R.id.example_row_tv_title);
// holder.tvDescription = (TextView) convertView.findViewById(R.id.example_row_tv_description);
// holder.bAction1 = (Button) convertView.findViewById(R.id.example_row_b_action_1);
// holder.bAction2 = (Button) convertView.findViewById(R.id.example_row_b_action_2);
// holder.bAction3 = (Button) convertView.findViewById(R.id.example_row_b_action_3);
// convertView.setTag(holder);
// } else {
// holder = (ViewHolder) convertView.getTag();
// }
//
// ((SwipeListView)parent).recycle(convertView, position);
//
// holder.ivImage.setImageDrawable(item.getIcon());
// holder.tvTitle.setText(item.getName());
// holder.tvDescription.setText(item.getPackageName());
//
//
// holder.bAction1.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = context.getPackageManager().getLaunchIntentForPackage(item.getPackageName());
// if (intent != null) {
// context.startActivity(intent);
// } else {
// Toast.makeText(context, R.string.cantOpen, Toast.LENGTH_SHORT).show();
// }
// }
// });
//
// holder.bAction2.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (isPlayStoreInstalled()) {
// context.startActivity(new Intent(Intent.ACTION_VIEW,
// Uri.parse("market://details?id=" + item.getPackageName())));
// } else {
// context.startActivity(new Intent(Intent.ACTION_VIEW,
// Uri.parse("http://play.google.com/store/apps/details?id=" + item.getPackageName())));
// }
// }
// });
//
// holder.bAction3.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Uri packageUri = Uri.parse("package:" + item.getPackageName());
// Intent uninstallIntent;
// if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
// } else {
// uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri);
// }
// context.startActivity(uninstallIntent);
// }
// });
//
//
// return convertView;
// }
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView ivImage;
TextView tvTitle;
Button bAction1;
Button bAction2;
public ViewHolder(View itemView) {
super(itemView);
ivImage = (ImageView) itemView.findViewById(R.id.example_row_iv_image);
tvTitle = (TextView) itemView.findViewById(R.id.example_row_tv_title);
bAction1 = (Button) itemView.findViewById(R.id.example_row_b_action_1);
bAction2 = (Button) itemView.findViewById(R.id.example_row_b_action_2);
}
}
private boolean isPlayStoreInstalled() {
Intent market = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=dummy"));
PackageManager manager = context.getPackageManager();
List list = manager.queryIntentActivities(market, 0);
return list.size() > 0;
}
}
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_add_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_autorenew_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_blur_linear_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_bug_report_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_exposure_plus_1_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_extension_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/ic_remove_24dp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable/toptint.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable-mdpi/custom_drag_frame.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/drawable-xxhdpi/item_selector.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/activity_drag.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/activity_launcher.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/activity_loadmore.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/countable_rv_adp.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/custom_bottom_progressbar.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/custom_refresh_activity.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/empty_view.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/empty_view_v2.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/exp_child.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/exp_parent.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/floating_view.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/floatingbutton_grid_layout.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/grid_item.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/header_love.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/item_node.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/item_swipeable.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/list_item.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/list_item_header.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/listurv.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/package_row.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/parallax_recyclerview_header.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/recycler_view_adapter.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/rv_item_linear.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/rv_item_stagger.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/rv_sample_1.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/rv_sample_2.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/simple_scroll_activity.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/simplefragment_viewpager_tabhost.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/simplefragment_viewpaper_fragment_parent.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/stick_header_item.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/swipe_list_view_activity.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/tab_indicator.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/layout/toolbar_loadmore.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/menu/admenu.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/menu/menu_main.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/CirclarImageViewCustomStyle.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/arrays.xml
================================================
22,0,0,30,22,0,30,0,30,0,52,30,0,30,26,30,60,0,60,15,60,15,60,30,60,15,85,15,85,15,108,0,85,15,108,30,117,0,147,0,147,0,177,0,147,0,147,32,198,0,176,30,198,0,206,0,206,0,228,30,176,30,202,30,0,35,12,42,12,42,24,35,24,35,12,28,0,35,12,28,0,21,12,28,12,28,24,21,24,35,24,21,24,21,12,14,0,21,12,14,0,21,0,7,12,14,0,7,12,14,24,7,24,7,12,0,0,7,12,0,@color/red@color/blue@color/yellow@color/green#FFC93437#FF375BF1#FFF7D23E#FF34A350
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/colors.xml
================================================
#ffffffff#fff9930d#ff2f8b2a#fff45f30#ff295db3#fff0f0f0#ffe0e0e0#ffddddff#ff9999ff#ffffdddd#ffff9999#5d1c23#793042#009688#00796b#eeff41#F4FF81#ffff3abb@color/background_material_dark@color/accent_material_dark
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/dimens.xml
================================================
16dp16dp16dp8dp4dp4dp72dp72dp240dp120dp180dp48dp100dp200dp16dp32dp4dp48dp40dp10sp15sp16sp
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/ids.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/scollables.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/strings.xml
================================================
UltimateRecyclerViewHello world!Settingshttps://github.com/cymcsg/UltimateRecyclerView
================================================
FILE: UltimateRecyclerView/app/src/main/res/values/styles.xml
================================================
================================================
FILE: UltimateRecyclerView/app/src/main/res/values-w820dp/dimens.xml
================================================
64dp
================================================
FILE: UltimateRecyclerView/build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.22"
}
}
allprojects {
repositories {
mavenCentral()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
//Library configurations
PUBLISH_GROUP_ID = 'com.marshalchen.ultimaterecyclerview'
PUBLISH_ARTIFACT_ID = 'library'
PUBLISH_VERSION = '0.9.1'
VERSION_CODE = 31
//Application
app_demo_versionCode = 31
app_demo_versionName = '1.7.6'
IS_UPLOADING = project.getGradle().startParameter.taskNames.any { it.contains('bintrayUpload') }
}
================================================
FILE: UltimateRecyclerView/gradle/wrapper/gradle-wrapper.properties
================================================
#Wed Jun 26 23:30:04 PDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip
================================================
FILE: UltimateRecyclerView/gradle.properties
================================================
ANDROID_BUILD_MIN_SDK_VERSION=21
ANDROID_BUILD_TARGET_SDK_VERSION=34
ANDROID_BUILD_SDK_VERSION=34
## Project-wide Gradle settings.
#
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
#
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx1024m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
#
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#Wed Feb 28 11:28:49 CST 2018
POM_DEVELOPER_ID=cymcsg
POM_SCM_URL=https\://github.com/cymcsg/UltimateRecyclerView
SNAPSHOT_REPOSITORY_URL=https\://oss.sonatype.org/content/repositories/snapshots
POM_LICENCE_DIST=repo
org.gradle.jvmargs=-Xmx1536M
#version check on @link https://github.com/square/leakcanary
#systemProp.http.proxyHost=127.0.0.1
POM_ARTIFACT_ID=library
POM_DEVELOPER_NAME=marshalchen
POM_LICENCE_URL=http\://www.apache.org/licenses/LICENSE-2.0.txt
POM_DESCRIPTION=A RecyclerView(advanced and flexible version of ListView) with refreshing,loading more,animation and many other features.
POM_LICENCE_NAME=The Apache Software License, Version 2.0
POM_NAME=ultimaterecyclerview
POM_PACKAGING=aar
LEAKCANARY=2.13
VERSION_NAME=0.8.1
VERSION_CODE=77
POM_SCM_DEV_CONNECTION=https\://github.com/cymcsg/UltimateRecyclerView.git
POM_URL=https\://github.com/cymcsg/UltimateRecyclerView
RELEASE_REPOSITORY_URL=https\://oss.sonatype.org/service/local/staging/deploy/maven2
POM_SCM_CONNECTION=https\://github.com/cymcsg/UltimateRecyclerView.git
GROUP=com.marshalchen.ultimaterecyclerview
systemProp.http.proxyPort=1087
android.useAndroidX=true
android.enableJetifier=true
================================================
FILE: UltimateRecyclerView/gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: UltimateRecyclerView/gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: UltimateRecyclerView/settings.gradle
================================================
include ':app', ':ultimaterecyclerview'
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/android-release-aar.gradle
================================================
// ./gradlew clean build generateRelease
apply plugin: 'maven'
def groupId = project.PUBLISH_GROUP_ID
def artifactId = project.PUBLISH_ARTIFACT_ID
def version = project.VERSION_NAME
def localReleaseDest = "${buildDir}/release/${version}"
task androidJavadocs(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.srcDirs
}
uploadArchives {
repositories.mavenDeployer {
pom.groupId = groupId
pom.artifactId = artifactId
pom.version = version
// Add other pom properties here if you want (developer details / licenses)
repository(url: "file://${localReleaseDest}")
}
}
task zipRelease(type: Zip) {
from localReleaseDest
destinationDir buildDir
archiveName "release-${version}.zip"
}
task generateRelease {
println "Release ${version} can be found at ${localReleaseDest}/"
println "Release ${version} zipped can be found ${buildDir}/release-${version}.zip"
}
generateRelease.dependsOn(uploadArchives)
generateRelease.dependsOn(zipRelease)
artifacts {
archives androidSourcesJar
//archives androidJavadocsJar
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/bintray-release-aar.gradle
================================================
apply plugin: 'bintray-release'
subprojects {
group = GROUP_NAME
version = VERSION_NAME
if (IS_UPLOADING && project.name in [MODULE_NAME]) {
println project.name
apply plugin: 'maven'
gradle.taskGraph.whenReady { taskGraph ->
taskGraph.getAllTasks().find {
it.path == ":$project.name:generatePomFileForMavenPublication"
}.doLast {
file("build/publications/maven/pom-default.xml").delete()
println 'Overriding pom-file to make sure we can sync to maven central!'
pom {
//noinspection GroovyAssignabilityCheck
project {
name "$project.name"
artifactId ARTIFACT_ID
packaging project.name == 'compiler' ? 'jar' : 'aar'
description DESCRIPTION
url SITE_URL
version VERSION_NAME
scm {
url GIT_URL
connection GIT_URL
developerConnection GIT_URL
}
licenses {
license {
name LICENSE
}
}
developers {
developer {
id DEVELOPER_ID
name DEVELOPER_NAME
email DEVELOPER_EMAIL
}
}
}
}.writeTo("build/publications/maven/pom-default.xml")
}
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/bintray_3_4.gradle
================================================
//apply plugin: 'bintray-release'
apply plugin: 'com.novoda.bintray-release'
publish {
userOrg = 'jjhesk'
groupId = 'com.hkm.ui'
artifactId = 'ultimaterecyclerview'
version = project.VERSION_NAME
uploadName = 'MenuURV'
description = "The super recycler for the menu"
website = 'https://github.com/jjhesk/BringItBackAdvanceSlidingMenu'
autoPublish = true
dryRun = false
issueTracker = "${website}/issues"
licences = [project.POM_LICENCE_NAME]
bintrayUser = userOrg
}
if (hasProperty('APIBKI')) {
publish.bintrayKey = property('APIBKI')
} else {
publish.bintrayKey = '17479d176480ed0232fe101b6555654a2624d7a0'
}
apply plugin: 'maven'
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/build.gradle
================================================
apply plugin: 'com.android.library'
android {
compileSdkVersion project.ANDROID_BUILD_SDK_VERSION as int
defaultConfig {
versionCode project.VERSION_CODE as int
versionName project.VERSION_NAME
minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
namespace 'com.marshalchen.ultimaterecyclerview'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
api 'androidx.appcompat:appcompat:1.6.1'
api 'androidx.recyclerview:recyclerview:1.3.2'
api "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
api 'in.srain.cube:ultra-ptr:1.0.11'
api 'com.github.bumptech.glide:glide:4.16.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
api 'jp.wasabeef:recyclerview-animators:4.0.2'
}
apply from: 'android-release-aar.gradle'
//apply from: 'maven-push.gradle'
//apply from: 'bintray-release-aar.gradle'
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/gradle.properties
================================================
POM_NAME=ultimaterecyclerview
POM_ARTIFACT_ID=library
POM_PACKAGING=aar
VERSION_NAME=0.9.1
VERSION_CODE=79
GROUP=com.marshalchen.ultimaterecyclerview
POM_DESCRIPTION=A RecyclerView(advanced and flexible version of ListView) with refreshing,loading more,animation and many other features.
POM_URL=https://github.com/cymcsg/UltimateRecyclerView
POM_SCM_URL=https://github.com/cymcsg/UltimateRecyclerView
POM_SCM_CONNECTION=https://github.com/cymcsg/UltimateRecyclerView.git
POM_SCM_DEV_CONNECTION=https://github.com/cymcsg/UltimateRecyclerView.git
POM_LICENCE_NAME=The Apache Software License, Version 2.0
POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo
POM_DEVELOPER_ID=cymcsg
POM_DEVELOPER_NAME=marshalchen
SNAPSHOT_REPOSITORY_URL=https://oss.sonatype.org/content/repositories/snapshots
RELEASE_REPOSITORY_URL=https://oss.sonatype.org/service/local/staging/deploy/maven2
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/maven-push.gradle
================================================
/*
* Copyright 2013 Chris Banes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'maven'
apply plugin: 'signing'
def isReleaseBuild() {
return VERSION_NAME.contains("SNAPSHOT") == false
}
def getReleaseRepositoryUrl() {
return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL
: "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
}
def getSnapshotRepositoryUrl() {
return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL
: "https://oss.sonatype.org/content/repositories/snapshots/"
}
def getRepositoryUsername() {
return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
}
def getRepositoryPassword() {
return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
}
afterEvaluate { project ->
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
pom.groupId = GROUP
pom.artifactId = POM_ARTIFACT_ID
pom.version = VERSION_NAME
repository(url: getReleaseRepositoryUrl()) {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
snapshotRepository(url: getSnapshotRepositoryUrl()) {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
pom.project {
name POM_NAME
packaging POM_PACKAGING
description POM_DESCRIPTION
url POM_URL
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
}
}
}
}
}
}
signing {
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
sign configurations.archives
}
task androidJavadocs(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.sourceFiles
}
artifacts {
archives androidSourcesJar
// archives androidJavadocsJar
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Volumes/MAC3/adt/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/androidTest/java/com/marshalchen/ultimaterecyclerview/ApplicationTest.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* Testing Fundamentals
*/
public class ApplicationTest extends ApplicationTestCase {
public ApplicationTest() {
super(Application.class);
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/AndroidManifest.xml
================================================
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/CustomUltimateRecyclerview.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import com.marshalchen.ultimaterecyclerview.ui.floatingactionbutton.FloatingActionButton;
import in.srain.cube.views.ptr.PtrFrameLayout;
/**
* Created by cym on 15/3/21.
*/
public class CustomUltimateRecyclerview extends UltimateRecyclerView {
public PtrFrameLayout mPtrFrameLayout;
public CustomUltimateRecyclerview(Context context) {
super(context);
}
public CustomUltimateRecyclerview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomUltimateRecyclerview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void initViews() {
//super.initViews();
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_recycler_view_layout, this);
mRecyclerView = (RecyclerView) view.findViewById(R.id.ultimate_list);
mSwipeRefreshLayout = null;
if (mRecyclerView != null) {
mRecyclerView.setClipToPadding(mClipToPadding);
if (mPadding != -1.1f) {
mRecyclerView.setPadding(mPadding, mPadding, mPadding, mPadding);
} else {
mRecyclerView.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
}
defaultFloatingActionButton = (FloatingActionButton) view.findViewById(R.id.defaultFloatingActionButton);
setDefaultScrollListener();
mEmpty = (ViewStub) view.findViewById(R.id.emptyview);
mFloatingButtonViewStub = (ViewStub) view.findViewById(R.id.floatingActionViewStub);
mEmpty.setLayoutResource(mEmptyId);
mFloatingButtonViewStub.setLayoutResource(mFloatingButtonId);
if (mEmptyId != 0)
mEmptyView = mEmpty.inflate();
mEmpty.setVisibility(View.GONE);
if (mFloatingButtonId != 0) {
mFloatingButtonView = mFloatingButtonViewStub.inflate();
mFloatingButtonView.setVisibility(View.VISIBLE);
}
}
public void setCustomSwipeToRefresh() {
mPtrFrameLayout = (PtrFrameLayout) findViewById(R.id.store_house_ptr_frame);
mPtrFrameLayout.setResistance(1.7f);
mPtrFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
mPtrFrameLayout.setDurationToClose(200);
mPtrFrameLayout.setDurationToCloseHeader(1000);
mPtrFrameLayout.setPullToRefresh(false);
mPtrFrameLayout.setKeepHeaderWhenRefresh(true);
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/DragDropTouchListener.java
================================================
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.marshalchen.ultimaterecyclerview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
/**
* Implementation of RecyclerView.OnItemTouchListener that allows reordering items in RecyclerView by dragging and dropping.
* Instance of this class should be added to RecylcerView using {@link RecyclerView#addOnItemTouchListener(RecyclerView.OnItemTouchListener)} method.
* Use something like this:
* dragDropTouchListener = new DragDropTouchListener(recyclerView, this) {
* Override
* protected void onItemSwitch(RecyclerView recyclerView, int from, int to) {
* adapter.swapPositions(from, to);
* adapter.notifyItemChanged(to);
* adapter.notifyItemChanged(from);
* Override
* protected void onItemDrop(RecyclerView recyclerView, int position) {
* }
* };
* }
* recyclerView.addOnItemTouchListener(dragDropTouchListener);
*
* Actual drag is started by calling {@link #startDrag()} somewhere later, for eg. in long touch listener
*/
public abstract class DragDropTouchListener implements RecyclerView.OnItemTouchListener {
private static final String LOG_TAG = "DRAG-DROP";
private static final int MOVE_DURATION = 150;
private RecyclerView recyclerView;
private Activity activity;
private Drawable dragHighlight;
private DisplayMetrics displayMetrics;
private final int scrollAmount;
private int downY = -1;
private int downX = -1;
private View mobileView;
private int mobileViewStartY = -1;
private int mobileViewCurrentPos = -1;
private int activePointerId;
private boolean dragging;
private boolean enabled = true;
public DragDropTouchListener(RecyclerView recyclerView, Activity activity) {
this.recyclerView = recyclerView;
this.activity = activity;
this.displayMetrics = recyclerView.getResources().getDisplayMetrics();
this.scrollAmount = (int) (50 / displayMetrics.density);
this.dragHighlight = recyclerView.getResources().getDrawable(R.drawable.drag_frame);
}
public DragDropTouchListener(RecyclerView recyclerView, Activity activity, Drawable dragHighlight) {
this(recyclerView, activity);
this.dragHighlight = dragHighlight;
}
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent event) {
if (!enabled) return false;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
return down(event);
case MotionEvent.ACTION_MOVE:
return dragging && move(event);
case MotionEvent.ACTION_UP:
return up(event);
case MotionEvent.ACTION_CANCEL:
return cancel(event);
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent event) {
if (!dragging) return;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
move(event);
break;
case MotionEvent.ACTION_UP:
up(event);
break;
case MotionEvent.ACTION_CANCEL:
cancel(event);
break;
}
}
/**
* Call this to indicate drag start
*/
public void startDrag() {
View viewUnder = recyclerView.findChildViewUnder(downX, downY);
if (viewUnder == null) return;
dragging = true;
mobileViewCurrentPos = recyclerView.getChildPosition(viewUnder);
int[] viewRawCoords = getViewRawCoords(viewUnder);
mobileView = copyViewAsImage(viewUnder);
mobileView.setX(viewRawCoords[0]);
mobileView.setY(viewRawCoords[1]);
mobileViewStartY = viewRawCoords[1];
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
activity.addContentView(mobileView, lp);
mobileView.bringToFront();
viewUnder.setVisibility(View.INVISIBLE);
}
private boolean down(MotionEvent event) {
activePointerId = event.getPointerId(0);
downY = (int) event.getY();
downX = (int) event.getX();
return false;
}
private boolean move(MotionEvent event) {
if (activePointerId == -1) {
return false;
}
int pointerIndex = event.findPointerIndex(activePointerId);
int currentY = (int) event.getY(pointerIndex);
int deltaY = currentY - downY;
int mobileViewY = mobileViewStartY + deltaY;
mobileView.setY(mobileViewY);
switchViewsIfNeeded();
scrollIfNeeded();
return true;
}
private void switchViewsIfNeeded() {
int pos = mobileViewCurrentPos;
int abovePos = pos - 1;
int belowPos = pos + 1;
View aboveView = getViewByPosition(abovePos);
View belowView = getViewByPosition(belowPos);
int mobileViewY = (int) mobileView.getY();
if (aboveView != null && aboveView.getTop() > -1 && mobileViewY < aboveView.getTop()) {
Log.d(LOG_TAG, String.format("Got aboveView with top = %s, for position = %s, %s", aboveView.getTop(), abovePos, aboveView));
doSwitch(aboveView, pos, abovePos);
}
if (belowView != null && belowView.getTop() > -1 && mobileViewY > belowView.getTop()) {
Log.d(LOG_TAG, String.format("Got belowView with top = %s, for position = %s, %s", belowView.getTop(), belowPos, belowView));
doSwitch(belowView, pos, belowPos);
}
}
private void doSwitch(final View switchView, final int originalViewPos, final int switchViewPos) {
View originalView = getViewByPosition(originalViewPos);
int switchViewTop = switchView.getTop();
int originalViewTop = originalView.getTop();
int delta = originalViewTop - switchViewTop;
onItemSwitch(recyclerView, originalViewPos, switchViewPos);
switchView.setVisibility(View.INVISIBLE);
originalView.setVisibility(View.VISIBLE);
originalView.setTranslationY(-delta);
originalView.animate().translationYBy(delta).setDuration(MOVE_DURATION);
mobileViewCurrentPos = switchViewPos;
}
private boolean up(MotionEvent event) {
if (dragging) {
onItemDrop(recyclerView, mobileViewCurrentPos);
}
reset();
return false;
}
private boolean cancel(MotionEvent event) {
reset();
return false;
}
private void reset() {
//Animate mobile view back to original position
final View view = getViewByPosition(mobileViewCurrentPos);
if (view != null && mobileView != null) {
float y = getViewRawCoords(view)[1];
mobileView.animate().y(y).setDuration(MOVE_DURATION).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.VISIBLE);
if (mobileView != null) {
ViewGroup parent = (ViewGroup) mobileView.getParent();
parent.removeView(mobileView);
mobileView = null;
}
}
});
}
dragging = false;
mobileViewStartY = -1;
mobileViewCurrentPos = -1;
}
private View getViewByPosition(int position) {
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForPosition(position);
return viewHolder == null ? null : viewHolder.itemView;
}
private boolean scrollIfNeeded() {
int height = recyclerView.getHeight();
int hoverViewTop = (int) mobileView.getY();
int hoverHeight = mobileView.getHeight();
if (hoverViewTop <= 0) {
recyclerView.scrollBy(0, -scrollAmount);
return true;
}
if (hoverViewTop + hoverHeight >= height) {
recyclerView.scrollBy(0, scrollAmount);
return true;
}
return false;
}
//Creates screenshot of a view
private ImageView copyViewAsImage(View v) {
//Clear ripple effect to not get into screenshot,
// need something more clever here
if (v instanceof FrameLayout) {
FrameLayout frameLayout = (FrameLayout) v;
Drawable foreground = frameLayout.getForeground();
if (foreground != null) foreground.setVisible(false, false);
} else {
if (v.getBackground() != null) v.getBackground().setVisible(false, false);
}
Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
v.draw(canvas);
//Drag highlight, usually border
if (dragHighlight != null) {
dragHighlight.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
dragHighlight.draw(canvas);
}
ImageView imageView = new ImageView(recyclerView.getContext());
imageView.setImageBitmap(bitmap);
return imageView;
}
private int[] getViewRawCoords(View locateView) {
View globalView = activity.findViewById(android.R.id.content);
int topOffset = displayMetrics.heightPixels - globalView.getMeasuredHeight();
int[] loc = new int[2];
locateView.getLocationOnScreen(loc);
loc[1] = loc[1] - topOffset;
return loc;
}
/**
* Enable/disable drag/drop
*
* @param enabled na
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Implementation usually do 2 things: change positions of items in RecyclerView.Adapter and notify it about changes
*
* @param recyclerView view the item is being dragged in
* @param from original (start) drag position within adapter
* @param to new drag position withing adapter
*/
protected abstract void onItemSwitch(RecyclerView recyclerView, int from, int to);
/**
* Item is dropped at given position
*
* @param recyclerView view the item is being dropped in
* @param position position of a drop within adapter
*/
protected abstract void onItemDrop(RecyclerView recyclerView, int position);
public void setCustomDragHighlight(Drawable dragHighlight) {
this.dragHighlight = dragHighlight;
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/ItemTouchListenerAdapter.java
================================================
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* /
*/
package com.marshalchen.ultimaterecyclerview;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.quickAdapter.AdmobAdapter;
/**
* As RecyclerView does not have standard way to add click listeners to the items,
* this RecyclerView.OnItemTouchListener intercepts touch events and translates them to simple
* Simply add it as follows:
*
* {@code
* recyclerView.addOnItemTouchListener(new ItemTouchListenerAdapter(recyclerView, this));
*
* }
*
*/
public class ItemTouchListenerAdapter extends GestureDetector.SimpleOnGestureListener implements RecyclerView.OnItemTouchListener {
public interface RecyclerViewOnItemClickListener {
void onItemClick(RecyclerView parent, View clickedView, int position);
void onItemLongClick(RecyclerView parent, View clickedView, int position);
}
private RecyclerViewOnItemClickListener listener;
private RecyclerView recyclerView;
private GestureDetector gestureDetector;
public ItemTouchListenerAdapter(
RecyclerView recyclerView,
RecyclerViewOnItemClickListener listener) {
if (recyclerView == null || listener == null) {
throw new IllegalArgumentException("RecyclerView and Listener arguments can not be null");
}
this.recyclerView = recyclerView;
this.listener = listener;
this.gestureDetector = new GestureDetector(recyclerView.getContext(), this);
}
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
gestureDetector.onTouchEvent(motionEvent);
return false;
}
@Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
@Override
public void onShowPress(MotionEvent e) {
View view = getChildViewUnder(e);
if (view != null) {
view.setPressed(true);
}
}
/**
* case out and fix the bug from offseted number from AdmobAdapter
* fixed by jjhesk
* one more thing is that the first item display in the list got to be clickable.
*
* @param position input position
* @return AdmobAdapter.POSITION_ON_AD meaning that the touch position is on the position of Adview
*/
private int shiftAdjustInt(int position) {
if (recyclerView.getAdapter() instanceof AdmobAdapter && position > 0 ) {
AdmobAdapter adp = (AdmobAdapter) recyclerView.getAdapter();
return adp.isPosOnAdView(position) ? AdmobAdapter.POSITION_ON_AD : adp.getFinalShiftPosition(position);
} else {
return position;
}
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
View view = getChildViewUnder(e);
if (view == null) return false;
view.setPressed(false);
int position = shiftAdjustInt(recyclerView.getChildAdapterPosition(view));
if (position != AdmobAdapter.POSITION_ON_AD) {
listener.onItemClick(recyclerView, view, position);
}
return true;
}
public void onLongPress(MotionEvent e) {
View view = getChildViewUnder(e);
if (view == null) return;
int position = shiftAdjustInt(recyclerView.getChildAdapterPosition(view));
if (position != AdmobAdapter.POSITION_ON_AD) {
listener.onItemLongClick(recyclerView, view, position);
}
view.setPressed(false);
}
@Nullable
private View getChildViewUnder(MotionEvent e) {
return recyclerView.findChildViewUnder(e.getX(), e.getY());
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/NormalUltimateViewAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.os.Build;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.itemTouchHelper.ItemTouchHelperAdapter;
import com.marshalchen.ultimaterecyclerview.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.util.Collections;
import java.util.List;
/**
* An abstract adapter which can be extended for Recyclerview
*/
public abstract class NormalUltimateViewAdapter extends RecyclerView.Adapter
implements StickyRecyclerHeadersAdapter, ItemTouchHelperAdapter {
protected View customLoadMoreView = null;
/**
* Set the header view of the adapter.
*
* @param customHeaderView na
*/
public void setCustomHeaderView(UltimateRecyclerView.CustomRelativeWrapper customHeaderView) {
this.customHeaderView = customHeaderView;
}
public UltimateRecyclerView.CustomRelativeWrapper getCustomHeaderView() {
return customHeaderView;
}
protected UltimateRecyclerView.CustomRelativeWrapper customHeaderView = null;
@Override
public UltimateRecyclerviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPES.FOOTER) {
UltimateRecyclerviewViewHolder viewHolder = new UltimateRecyclerviewViewHolder(customLoadMoreView);
if (getAdapterItemCount() == 0)
viewHolder.itemView.setVisibility(View.GONE);
return viewHolder;
} else if (viewType == VIEW_TYPES.HEADER) {
if (customHeaderView != null)
return new UltimateRecyclerviewViewHolder(customHeaderView);
} else if (viewType == VIEW_TYPES.CHANGED_FOOTER) {
UltimateRecyclerviewViewHolder viewHolder = new UltimateRecyclerviewViewHolder(customLoadMoreView);
if (getAdapterItemCount() == 0)
viewHolder.itemView.setVisibility(View.GONE);
return viewHolder;
}
// else if (viewType==VIEW_TYPES.STICKY_HEADER){
// return new UltimateRecyclerviewViewHolder(LayoutInflater.from(parent.getContext())
// .inflate(R.layout.stick_header_item, parent, false));
// }
return onCreateViewHolder(parent);
}
public abstract UltimateRecyclerviewViewHolder onCreateViewHolder(ViewGroup parent);
/**
* Using a custom LoadMoreView
*
* @param customview the inflated view
*/
public void setCustomLoadMoreView(View customview) {
customLoadMoreView = customview;
}
/**
* Changing the loadmore view
*
* @param customview the inflated view
*/
public void swipeCustomLoadMoreView(View customview) {
customLoadMoreView = customview;
isLoadMoreChanged = true;
}
public View getCustomLoadMoreView() {
return customLoadMoreView;
}
public boolean isLoadMoreChanged = false;
@Override
public int getItemViewType(int position) {
if (position == getItemCount() - 1 && customLoadMoreView != null) {
if (isLoadMoreChanged) {
return VIEW_TYPES.CHANGED_FOOTER;
} else {
return VIEW_TYPES.FOOTER;
}
} else if (position == 0 && customHeaderView != null) {
return VIEW_TYPES.HEADER;
} else
return VIEW_TYPES.NORMAL;
}
/**
* Returns the total number of items in the data set hold by the adapter.
*
* @return The total number of items in this adapter.
*/
@Override
public int getItemCount() {
int headerOrFooter = 0;
if (customHeaderView != null) headerOrFooter++;
if (customLoadMoreView != null) headerOrFooter++;
return getAdapterItemCount() + headerOrFooter;
}
/**
* Returns the number of items in the adapter bound to the parent RecyclerView.
*
* @return The number of items in the bound adapter
*/
public abstract int getAdapterItemCount();
public void toggleSelection(int pos) {
notifyItemChanged(pos);
}
public void clearSelection(int pos) {
notifyItemChanged(pos);
}
public void setSelected(int pos) {
notifyItemChanged(pos);
}
/**
* Swap the item of list
*
* @param list data list
* @param from position from
* @param to position to
*/
public void swapPositions(List> list, int from, int to) {
if (customHeaderView != null) {
from--;
to--;
}
Collections.swap(list, from, to);
}
/**
* Insert a item to the list of the adapter
*
* @param list data list
* @param object object T
* @param position position
* @param in T
*/
public void insert(List list, T object, int position) {
list.add(position, object);
if (customHeaderView != null) position++;
notifyItemInserted(position);
}
/**
* Remove a item of the list of the adapter
*
* @param list data list
* @param position position
*/
public void remove(List> list, int position) {
if (list.size() > 0) {
list.remove(customHeaderView != null ? position - 1 : position);
notifyItemRemoved(position);
}
}
/**
* Clear the list of the adapter
*
* @param list data list
*/
public void clear(List> list) {
int size = list.size();
list.clear();
notifyItemRangeRemoved(0, size);
}
@Override
public long getHeaderId(int position) {
if (customHeaderView != null && position == 0) return -1;
if (customLoadMoreView != null && position >= getItemCount() - 1) return -1;
if (getAdapterItemCount() > 0)
return generateHeaderId(position);
else return -1;
}
public abstract long generateHeaderId(int position);
protected class VIEW_TYPES {
public static final int NORMAL = 0;
public static final int HEADER = 1;
public static final int FOOTER = 2;
public static final int CHANGED_FOOTER = 3;
}
protected enum AdapterAnimationType {
AlphaIn,
SlideInBottom,
ScaleIn,
SlideInLeft,
SlideInRight,
}
/**
* Animations when loading the adapter
*
* @param view the view
* @param type the type of the animation
* @return the animator in array
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected Animator[] getAdapterAnimations(View view, AdapterAnimationType type) {
if (type == AdapterAnimationType.ScaleIn) {
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", .5f, 1f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", .5f, 1f);
return new ObjectAnimator[]{scaleX, scaleY};
} else if (type == AdapterAnimationType.AlphaIn) {
return new Animator[]{ObjectAnimator.ofFloat(view, "alpha", .5f, 1f)};
} else if (type == AdapterAnimationType.SlideInBottom) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0)
};
} else if (type == AdapterAnimationType.SlideInLeft) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationX", -view.getRootView().getWidth(), 0)
};
} else if (type == AdapterAnimationType.SlideInRight) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationX", view.getRootView().getWidth(), 0)
};
}
return null;
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
notifyDataSetChanged();
}
protected OnStartDragListener mDragStartListener = null;
/**
* Listener for manual initiation of a drag.
*/
public interface OnStartDragListener {
/**
* Called when a view is requesting a start of a drag.
*
* @param viewHolder The holder of the view to drag.
*/
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/ObservableScrollState.java
================================================
/*
* Copyright 2014 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview;
/**
* Constants that indicates the scroll state of the Scrollable widgets.
*/
public enum ObservableScrollState {
/**
* Widget is stopped.
* This state does not always mean that this widget have never been scrolled.
*/
STOP,
/**
* Widget is scrolled up by swiping it down.
*/
UP,
/**
* Widget is scrolled down by swiping it up.
*/
DOWN,
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/ObservableScrollViewCallbacks.java
================================================
/*
* Copyright 2014 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview;
/**
* Callbacks for Scrollable widgets.
*/
public interface ObservableScrollViewCallbacks {
/**
* Called when the scroll change events occurred.
* This won't be called just after the view is laid out, so if you'd like to
* initialize the position of your views with this method, you should call this manually
* or invoke scroll as appropriate.
*
* @param scrollY scroll position in Y axis
* @param firstScroll true when this is called for the first time in the consecutive motion events
* @param dragging true when the view is dragged and false when the view is scrolled in the inertia
*/
void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging);
/**
* Called when the down motion event occurred.
*/
void onDownMotionEvent();
/**
* Called when the dragging ended or canceled.
*
* @param observableScrollState state to indicate the scroll direction
*/
void onUpOrCancelMotionEvent(ObservableScrollState observableScrollState);
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/RecyclerItemClickListener.java
================================================
/*
* Copyright(c) 2015 Marshal Chen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildPosition(childView));
return true;
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/Scrollable.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.ObservableScrollViewCallbacks;
/**
* Provides common API for observable and scrollable widgets.
*/
public interface Scrollable {
/**
* Sets a callback listener.
*
* @param listener listener to set
*/
void setScrollViewCallbacks(ObservableScrollViewCallbacks listener);
/**
* Scrolls vertically to the absolute Y.
* Implemented classes are expected to scroll to the exact Y pixels from the top,
* but it depends on the type of the widget.
*
* @param y vertical position to scroll to
*/
void scrollVerticallyTo(int y);
/**
* Returns the current Y of the scrollable view.
*
* @return current Y pixel
*/
int getCurrentScrollY();
/**
* Sets a touch motion event delegation ViewGroup.
* This is used to pass motion events back to parent view.
* It's up to the implementation classes whether or not it works.
*
* @param viewGroup ViewGroup object to dispatch motion events
*/
void setTouchInterceptionViewGroup(ViewGroup viewGroup);
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/SwipeDismissTouchListener.java
================================================
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
@Deprecated
public class SwipeDismissTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private View mView;
private SwipeDismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private Object mToken;
private VelocityTracker mVelocityTracker;
private float mTranslationX;
/**
* The callback interface used by {@link com.marshalchen.ultimaterecyclerview.SwipeDismissTouchListener} to inform its client
* about a successful dismissal of the view for which it was created.
*/
public interface SwipeDismissCallbacks {
/**
* Called to determine whether the view can be dismissed.
*
* @param token na
* @return na
*/
boolean canDismiss(Object token);
/**
* Called when the user has indicated they she would like to dismiss the view.
*
* @param view The originating {@link android.view.View} to be dismissed.
* @param token The optional token passed to this object's constructor.
*/
void onDismiss(View view, Object token);
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given view.
*
* @param view The view to make dismissable.
* @param token An optional token/cookie object to be passed through to the callback.
* @param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss this view.
*/
public SwipeDismissTouchListener(View view, Object token, SwipeDismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(view.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = view.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mView = view;
mToken = token;
mCallbacks = callbacks;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// offset because the view is translated during swipe
motionEvent.offsetLocation(mTranslationX, 0);
if (mViewWidth < 2) {
mViewWidth = mView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
// TODO: ensure this is a finger, and set a flag
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
if (mCallbacks.canDismiss(mToken)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
}
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
mView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
performDismiss();
}
});
} else if (mSwiping) {
// cancel
mView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
mView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
mView.getParent().requestDisallowInterceptTouchEvent(true);
// Cancel listview's touch
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex() <<
MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mTranslationX = deltaX;
mView.setTranslationX(deltaX - mSwipingSlop);
// TODO: use an ease-out interpolator or such
mView.setAlpha(Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private void performDismiss() {
// Animate the dismissed view to zero-height and then fire the dismiss callback.
// This triggers layout on each animation frame; in the future we may want to do something
// smarter and more performant.
URLogs.d("performDismiss");
final ViewGroup.LayoutParams lp = mView.getLayoutParams();
final int originalHeight = mView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCallbacks.onDismiss(mView, mToken);
// Reset view presentation
mView.setAlpha(1f);
mView.setTranslationX(0);
lp.height = originalHeight;
mView.setLayoutParams(lp);
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
// if (lp.height > 100)
mView.setLayoutParams(lp);
// mView.setVisibility(View.GONE);
}
});
animator.start();
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/SwipeableUltimateRecyclerview.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import com.marshalchen.ultimaterecyclerview.swipelistview.SwipeListView;
import com.marshalchen.ultimaterecyclerview.swipelistview.SwipeListViewListener;
import com.marshalchen.ultimaterecyclerview.ui.VerticalSwipeRefreshLayout;
import com.marshalchen.ultimaterecyclerview.ui.floatingactionbutton.FloatingActionButton;
/**
* Created by MarshalChen on 15-6-5.
*/
public class SwipeableUltimateRecyclerview extends UltimateRecyclerView {
public SwipeableUltimateRecyclerview(Context context) {
super(context);
}
public SwipeableUltimateRecyclerview(Context context, AttributeSet attrs) {
super(context, attrs);
((SwipeListView)mRecyclerView).init(attrs);
}
public SwipeableUltimateRecyclerview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
((SwipeListView)mRecyclerView).init(attrs);
}
@Override
protected void initViews() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.swipeable_ultimate_recycler_view_layout, this);
mRecyclerView = (SwipeListView) view.findViewById(R.id.ultimate_list);
mSwipeRefreshLayout = (VerticalSwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
setScrollbars();
mSwipeRefreshLayout.setEnabled(false);
if (mRecyclerView != null) {
mRecyclerView.setClipToPadding(mClipToPadding);
if (mPadding != -1.1f) {
mRecyclerView.setPadding(mPadding, mPadding, mPadding, mPadding);
} else {
mRecyclerView.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
}
defaultFloatingActionButton = (FloatingActionButton) view.findViewById(R.id.defaultFloatingActionButton);
setDefaultScrollListener();
mEmpty = (ViewStub) view.findViewById(R.id.emptyview);
mFloatingButtonViewStub = (ViewStub) view.findViewById(R.id.floatingActionViewStub);
mEmpty.setLayoutResource(mEmptyId);
mFloatingButtonViewStub.setLayoutResource(mFloatingButtonId);
if (mEmptyId != 0)
mEmptyView = mEmpty.inflate();
mEmpty.setVisibility(View.GONE);
if (mFloatingButtonId != 0) {
mFloatingButtonView = mFloatingButtonViewStub.inflate();
mFloatingButtonView.setVisibility(View.VISIBLE);
}
}
public void setSwipeListViewListener(SwipeListViewListener swipeListViewListener) {
((SwipeListView)mRecyclerView).swipeListViewListener = swipeListViewListener;
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/SwipeableUltimateViewAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import com.marshalchen.ultimaterecyclerview.swipe.SwipeItemManagerImpl;
import com.marshalchen.ultimaterecyclerview.swipe.SwipeItemManagerInterface;
import com.marshalchen.ultimaterecyclerview.swipe.SwipeLayout;
import java.util.List;
/**
* An abstract adapter which can be extended for Recyclerview
*/
public abstract class SwipeableUltimateViewAdapter
extends easyRegularAdapter
implements SwipeItemManagerInterface {
public SwipeableUltimateViewAdapter(List list) {
super(list);
}
protected SwipeItemManagerImpl mItemManger = new SwipeItemManagerImpl(this);
/**
* binding normal view holder
*
* @param holder holder class
* @param data data
* @param position position
*/
@Override
protected void withBindHolder(UltimateRecyclerviewViewHolder holder, T data, int position) {
mItemManger.updateConvertView(holder, position);
}
@Override
protected void onBindAdViewHolder(RecyclerView.ViewHolder holder, int pos) {
mItemManger.updateConvertView((UltimateRecyclerviewViewHolder) holder, pos);
}
@Override
protected void onBindCustomViewHolder(RecyclerView.ViewHolder holder, int pos) {
mItemManger.updateConvertView((UltimateRecyclerviewViewHolder) holder, pos);
}
@Override
protected void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int pos) {
// mItemManger.updateConvertView((UltimateRecyclerviewViewHolder) holder, pos);
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int pos) {
// mItemManger.updateConvertView((UltimateRecyclerviewViewHolder) holder, pos);
}
@Override
public void openItem(int position) {
mItemManger.openItem(position);
}
@Override
public void closeItem(int position) {
mItemManger.closeItem(position);
}
@Override
public void closeAllExcept(SwipeLayout layout) {
mItemManger.closeAllExcept(layout);
}
@Override
public List getOpenItems() {
return mItemManger.getOpenItems();
}
@Override
public List getOpenLayouts() {
return mItemManger.getOpenLayouts();
}
@Override
public void removeShownLayouts(SwipeLayout layout) {
mItemManger.removeShownLayouts(layout);
}
@Override
public boolean isOpen(int position) {
return mItemManger.isOpen(position);
}
@Override
public SwipeItemManagerImpl.Mode getMode() {
return mItemManger.getMode();
}
@Override
public void setMode(SwipeItemManagerImpl.Mode mode) {
mItemManger.setMode(mode);
}
public static class BaseSwipeableViewHolder extends RecyclerView.ViewHolder {
public SwipeLayout swipeLayout = null;
public SwipeLayout.OnLayout onLayoutListener = null;
public SwipeLayout.SwipeListener swipeMemory = null;
public int position = -1;
public BaseSwipeableViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.recyclerview_swipe);
}
}
@Override
public void insert(List new_data) {
super.insert(new_data);
closeAllExcept(null);
}
@Override
public void removeAll() {
super.removeAll();
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/URLogs.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.util.Log;
/**
* Only for debug
*/
public final class URLogs {
private static boolean sIsLogEnabled = true;
private static String sApplicationTag = "Chen";
private static final String TAG_CONTENT_PRINT = "%s:%s.%s:%d";
private static StackTraceElement getCurrentStackTraceElement() {
return Thread.currentThread().getStackTrace()[4];
}
public static void trace() {
if (sIsLogEnabled) {
Log.d(sApplicationTag,
getContent(getCurrentStackTraceElement()));
}
}
private static String getContent(StackTraceElement trace) {
return String.format(TAG_CONTENT_PRINT, sApplicationTag,
trace.getClassName(), trace.getMethodName(),
trace.getLineNumber());
}
private static String getContents(StackTraceElement trace) {
return String.format("%s:%s:%d", sApplicationTag,
trace.getMethodName(),
trace.getLineNumber());
}
public static void traceStack() {
if (sIsLogEnabled) {
traceStack(sApplicationTag, Log.ERROR);
}
}
public static void traceStack(String tag, int priority) {
if (sIsLogEnabled) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Log.println(priority, tag, stackTrace[4].toString());
StringBuilder str = new StringBuilder();
String prevClass = null;
for (int i = 5; i < stackTrace.length; i++) {
String className = stackTrace[i].getFileName();
int idx = className.indexOf(".java");
if (idx >= 0) {
className = className.substring(0, idx);
}
if (prevClass == null || !prevClass.equals(className)) {
str.append(className.substring(0, idx));
}
prevClass = className;
str.append(".").append(stackTrace[i].getMethodName())
.append(":").append(stackTrace[i].getLineNumber())
.append("->");
}
Log.println(priority, tag, str.toString());
}
}
/**
* Send a VERBOSE log message.
*
* @param msg na
*/
public static void v(String msg) {
if (sIsLogEnabled) {
Log.v(sApplicationTag, getContents(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send a DEBUG log message.
*
* @param tag na
* @param msg na
*/
public static void d(String tag, String msg) {
if (sIsLogEnabled) {
Log.d(tag, getContent(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send a DEBUG log message.
*
* @param msg na
*/
public static void d(String msg) {
if (sIsLogEnabled) {
Log.d(sApplicationTag, getContents(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send an INFO log message.
*
* @param tag na
* @param msg na
*/
public static void i(String tag, String msg) {
if (sIsLogEnabled) {
Log.i(tag, getContent(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* @param message na
* @param args na
*/
public static void d(String message, Object... args) {
if (sIsLogEnabled) {
d(String.format(message, args));
}
}
/**
* Send a WARN log message.
*
* @param tag na
* @param msg na
*/
public static void w(String tag, String msg) {
if (sIsLogEnabled) {
Log.w(tag, getContent(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send an ERROR log message.
*
* @param tag na
* @param msg na
*/
public static void e(String tag, String msg) {
if (sIsLogEnabled) {
Log.e(tag, getContent(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send an INFO log message.
*
* @param msg na
*/
public static void i(String msg) {
if (sIsLogEnabled) {
Log.i(sApplicationTag, getContent(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send a WARN log message.
*
* @param msg na
*/
public static void w(String msg) {
if (sIsLogEnabled) {
Log.w(sApplicationTag, getContent(getCurrentStackTraceElement()) + ">" + msg);
}
}
/**
* Send an ERROR log message.
*
* @param msg na
*/
public static void e(String msg) {
if (sIsLogEnabled) {
Log.e(sApplicationTag, getContent(getCurrentStackTraceElement()) + "\n>" + msg);
}
}
/**
* Send an ERROR log message.
*
* @param exception na
*/
public static void e(Exception exception) {
if (sIsLogEnabled) {
Log.e(sApplicationTag, getContent(getCurrentStackTraceElement()) + "\n>" + exception.getMessage());
exception.printStackTrace();
}
}
/**
* Send an ERROR log message.
*
* @param exception na
* @param string na
*/
public static void e(Exception exception, String string) {
if (sIsLogEnabled) {
Log.e(sApplicationTag, getContent(getCurrentStackTraceElement()) + "\n>" + exception.getMessage() + "\n>" + exception.getStackTrace() + " " + string);
exception.printStackTrace();
}
}
/**
* Send an ERROR log message.
*
* @param string na
* @param exception na
*/
public static void e(String string, Exception exception) {
if (sIsLogEnabled) {
Log.e(sApplicationTag, getContent(getCurrentStackTraceElement()) + "\n>" + exception.getMessage() + "\n>" + exception.getStackTrace() + " " + string);
exception.printStackTrace();
}
}
/**
* Send an ERROR log message.
*
* @param tag na
* @param message na
* @param exception na
*/
public static void e(String tag, String message, Exception exception) {
if (sIsLogEnabled) {
Log.e(tag, getContent(getCurrentStackTraceElement()) + "\n>" + exception.getMessage() + "\n>" + exception.getStackTrace() + " " + message);
exception.printStackTrace();
}
}
public static boolean issIsLogEnabled() {
return sIsLogEnabled;
}
/**
* Set if the Logs print log or not
*
* @param sIsLogEnabled na
*/
public static void setsIsLogEnabled(boolean sIsLogEnabled) {
URLogs.sIsLogEnabled = sIsLogEnabled;
}
public static String getsApplicationTag() {
return sApplicationTag;
}
public static void setsApplicationTag(String sApplicationTag) {
URLogs.sApplicationTag = sApplicationTag;
}
public static String getTagContentPrint() {
return TAG_CONTENT_PRINT;
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/UltimateDifferentViewTypeAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.multiViewTypes.DataBinder;
import java.util.HashMap;
import java.util.Map;
/**
* An adapter which support different layout
*/
public abstract class UltimateDifferentViewTypeAdapter> extends UltimateViewAdapter {
private Map mBinderMap = new HashMap<>();
protected class VIEW_TYPES extends UltimateViewAdapter.VIEW_TYPES {
public static final int MULTI_VIEWS = 5;
}
@Override
public UltimateRecyclerviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// if (viewType == VIEW_TYPES.HEADER||viewType ==VIEW_TYPES.FOOTER
// ||viewType==VIEW_TYPES.CHANGED_FOOTER) {
// return super.onCreateViewHolder(parent, viewType);
// } else
return getDataBinder(viewType).newViewHolder(parent);
}
@Override
public void onBindViewHolder(UltimateRecyclerviewViewHolder viewHolder, int position) {
//int binderPosition = getBinderPosition(position);
getDataBinder(viewHolder.getItemViewType()).bindViewHolder(viewHolder, position);
}
@Override
public int getItemCount() {
int itemCount = 0;
for (DataBinder binder : mBinderMap.values()) {
itemCount += binder.getItemCount();
}
return itemCount;
}
@Override
public int getItemViewType(int position) {
// int type = super.getItemViewType(position);
// if (type == VIEW_TYPES.NORMAL) {
// return getEnumFromPosition(position).ordinal();
// } else {
// return type;
// }
return getEnumFromPosition(position).ordinal();
}
public T getDataBinder(int viewType) {
return getDataBinder(getEnumFromOrdinal(viewType));
}
public int getPosition(DataBinder binder, int binderPosition) {
E targetViewType = getEnumFromBinder(binder);
for (int i = 0; i < getItemCount(); i++) {
if (targetViewType == getEnumFromPosition(i)) {
binderPosition--;
if (binderPosition <= 0) {
return i;
}
}
}
return getItemCount();
}
public int getBinderPosition(int position) {
E targetViewType = getEnumFromPosition(position);
int binderPosition = -1;
for (int i = 0; i <= position; i++) {
if (targetViewType == getEnumFromPosition(i)) {
binderPosition++;
}
}
if (binderPosition == -1) {
throw new IllegalArgumentException("Invalid Argument");
}
return binderPosition;
}
public void notifyBinderItemRangeChanged(DataBinder binder, int positionStart, int itemCount) {
for (int i = positionStart; i <= itemCount; i++) {
notifyItemChanged(getPosition(binder, i));
}
}
public void notifyBinderItemRangeInserted(DataBinder binder, int positionStart, int itemCount) {
for (int i = positionStart; i <= itemCount; i++) {
notifyItemInserted(getPosition(binder, i));
}
}
public void notifyBinderItemRangeRemoved(DataBinder binder, int positionStart, int itemCount) {
for (int i = positionStart; i <= itemCount; i++) {
notifyItemRemoved(getPosition(binder, i));
}
}
public void notifyBinderItemChanged(DataBinder binder, int binderPosition) {
notifyItemChanged(getPosition(binder, binderPosition));
}
public void notifyBinderItemInserted(DataBinder binder, int binderPosition) {
notifyItemInserted(getPosition(binder, binderPosition));
}
public void notifyBinderItemMoved(DataBinder binder, int fromPosition, int toPosition) {
notifyItemMoved(getPosition(binder, fromPosition), getPosition(binder, toPosition));
}
public void notifyBinderItemRemoved(DataBinder binder, int binderPosition) {
notifyItemRemoved(getPosition(binder, binderPosition));
}
public abstract E getEnumFromPosition(int position);
public abstract E getEnumFromOrdinal(int ordinal);
public E getEnumFromBinder(DataBinder binder) {
for (Map.Entry entry : mBinderMap.entrySet()) {
if (entry.getValue().equals(binder)) {
return entry.getKey();
}
}
throw new IllegalArgumentException("Invalid Data Binder");
}
public T getDataBinder(E e) {
return (T) mBinderMap.get(e);
}
public Map getBinderMap() {
return mBinderMap;
}
public void putBinder(E e, DataBinder binder) {
mBinderMap.put(e, binder);
}
public void removeBinder(E e) {
mBinderMap.remove(e);
}
public void clearBinderMap() {
mBinderMap.clear();
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/UltimateGridLayoutAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.annotation.TargetApi;
import android.os.Build;
import androidx.annotation.LayoutRes;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import java.util.List;
/**
* Created by hesk on 27/1/16.
*/
public abstract class UltimateGridLayoutAdapter extends easyRegularAdapter {
private boolean mValid = true;
private int span_columns;
public UltimateGridLayoutAdapter(List items) {
super(items);
span_columns = 1;
}
public void setSpanColumns(int columns) {
span_columns = columns;
}
private int normalDataConv(final int rpos) {
int orgin = rpos;
int size = getAdapterItemCount();
if (hasHeaderView()) orgin -= 1;
int out = orgin >= size - 1 ? size - 1 : orgin;
return out;
}
protected View getViewById(@LayoutRes final int layoutId, ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
return view;
}
@Override
public UltimateRecyclerviewViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
return new UltimateRecyclerviewViewHolder(parent);
}
@Override
public int getAdapterItemCount() {
return mValid ? super.getAdapterItemCount() : 0;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public long generateHeaderId(int position) {
return View.generateViewId();
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final int current_type = getItemViewType(position);
if (VIEW_TYPES.HEADER == current_type) {
onBindHeaderViewHolder(holder, position);
} else if (VIEW_TYPES.NORMAL == current_type) {
bindNormal((BINDER) holder, getItem(getItemDataPosFromInternalPos(position)), position);
} else if (VIEW_TYPES.FOOTER == current_type) {
onFooterCustomerization(holder, position);
}
}
protected void onFooterCustomerization(RecyclerView.ViewHolder view, int position) {
}
/**
* normally you dont need to do anything for this implementation.
*
* @param holder the data holder
* @param position position to render
*/
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {
// Log.d("ascc", position + " : ");
}
protected abstract void bindNormal(BINDER b, DATA data, final int position);
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/UltimateRecyclerView.java
================================================
/*
* Copyright(c) 2015 Marshal Chen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.os.Parcelable;
import androidx.annotation.ColorInt;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.marshalchen.ultimaterecyclerview.ui.DividerItemDecoration;
import com.marshalchen.ultimaterecyclerview.ui.VerticalSwipeRefreshLayout;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;
import com.marshalchen.ultimaterecyclerview.ui.floatingactionbutton.FloatingActionButton;
import com.marshalchen.ultimaterecyclerview.ui.floatingactionbutton.FloatingActionsMenu;
import com.marshalchen.ultimaterecyclerview.uiUtils.RecyclerViewPositionHelper;
import com.marshalchen.ultimaterecyclerview.uiUtils.SavedStateScrolling;
/**
* UltimateRecyclerView is a recyclerview which contains many features like swipe to dismiss,animations,drag drop etc.
*/
public class UltimateRecyclerView extends FrameLayout implements Scrollable {
/**
* TRIGGERED ON NOTIFIY ITEMS
*/
public static int EMPTY_CLEAR_ALL = 0;
public static int EMPTY_SHOW_LOADMORE_ONLY = 1;
public static int EMPTY_KEEP_HEADER = 2;
public static int EMPTY_KEEP_HEADER_AND_LOARMORE = 3;
/**
* TRIGGERED ON SETTING ADAPTER TO THE URV
*/
public static int STARTWITH_OFFLINE_ITEMS = 0;
public static int STARTWITH_ONLINE_ITEMS = 1;
private int policy_empty, policy_init;
public RecyclerView mRecyclerView;
protected FloatingActionButton defaultFloatingActionButton;
private OnLoadMoreListener onLoadMoreListener;
private int lastVisibleItemPosition;
protected RecyclerView.OnScrollListener mOnScrollListener;
protected LAYOUT_MANAGER_TYPE layoutManagerType;
private boolean automaticLoadMoreEnabled = false;
protected int mPadding;
protected int mPaddingTop;
protected int mPaddingBottom;
protected int mPaddingLeft;
protected int mPaddingRight;
//protected int mEmptyViewPolicy;
protected boolean mClipToPadding;
private UltimateViewAdapter mAdapter;
// Fields that should be saved onSaveInstanceState
private int mPrevFirstVisiblePosition;
private int mPrevFirstVisibleChildHeight = -1;
private int mPrevScrolledChildrenHeight;
private int mPrevScrollY;
private int mScrollY;
private SparseIntArray mChildrenHeights = new SparseIntArray();
// Fields that don't need to be saved onSaveInstanceState
private ObservableScrollState mObservableScrollState;
private ObservableScrollViewCallbacks mCallbacks;
//private ScrollState mScrollState;
private boolean mFirstScroll;
private boolean mDragging;
private boolean mIntercepted;
private boolean mIsLoadMoreWidgetEnabled = false;
private MotionEvent mPrevMoveEvent;
private ViewGroup mTouchInterceptionViewGroup;
/**
* custom load more progress bar
*/
private View mLoadMoreView;
/**
* empty view group
*/
protected ViewStub mEmpty;
protected View mEmptyView;
protected int mEmptyId;
protected emptyViewOnShownListener mEmptyViewListener;
/**
* the floating button group
*/
protected ViewStub mFloatingButtonViewStub;
protected View mFloatingButtonView;
protected int mFloatingButtonId;
protected int[] defaultSwipeToDismissColors = null;
public int showLoadMoreItemNum = 3;
public VerticalSwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerViewPositionHelper mRecyclerViewHelper;
private CustomRelativeWrapper mHeader;
private int mTotalYScrolled;
private final float SCROLL_MULTIPLIER = 0.5f;
private OnParallaxScroll mParallaxScroll;
private static boolean isParallaxHeader = false;
private LayoutInflater inflater;
/**
* control to show the loading view first when list is initiated at the beginning
* true - assume there is a buffer to load things before and the adapter suppose zero data at the beignning
* false - assume there is data to show at the beginning level
*/
private boolean isFirstLoadingOnlineAdapter = false;
// added by Sevan Joe to support scrollbars
private static final int SCROLLBARS_NONE = 0;
private static final int SCROLLBARS_VERTICAL = 1;
private static final int SCROLLBARS_HORIZONTAL = 2;
private int mScrollbarsStyle;
private int mVisibleItemCount = 0;
private int mTotalItemCount = 0;
private int previousTotal = 0;
private int mFirstVisibleItem;
public UltimateRecyclerView(Context context) {
super(context);
initViews();
}
public UltimateRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
initAttrs(attrs);
initViews();
}
public UltimateRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(attrs);
initViews();
}
public void setRecylerViewBackgroundColor(@ColorInt int color) {
mRecyclerView.setBackgroundColor(color);
}
protected void initViews() {
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ultimate_recycler_view_layout, this);
mRecyclerView = (RecyclerView) view.findViewById(R.id.ultimate_list);
mSwipeRefreshLayout = (VerticalSwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
setScrollbars();
mSwipeRefreshLayout.setEnabled(false);
if (mRecyclerView != null) {
mRecyclerView.setClipToPadding(mClipToPadding);
if (mPadding != -1.1f) {
mRecyclerView.setPadding(mPadding, mPadding, mPadding, mPadding);
} else {
mRecyclerView.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
}
defaultFloatingActionButton = (FloatingActionButton) view.findViewById(R.id.defaultFloatingActionButton);
setDefaultScrollListener();
/**
* empty view setup
*/
mEmpty = (ViewStub) view.findViewById(R.id.emptyview);
if (mEmptyId != 0) {
mEmpty.setLayoutResource(mEmptyId);
mEmptyView = mEmpty.inflate();
mEmpty.setVisibility(View.GONE);
}
/**
* floating button setup
*/
mFloatingButtonViewStub = (ViewStub) view.findViewById(R.id.floatingActionViewStub);
mFloatingButtonViewStub.setLayoutResource(mFloatingButtonId);
}
/**
* retrieve the empty view from the core
*
* @return the view item
*/
public View getEmptyView() {
return mEmptyView;
}
private void setPolicies(final int policyEmtpyView, final int policyInitialization) {
// setPolices(policyEmtpyView, policyInitialization);
policy_empty = policyEmtpyView;
policy_init = policyInitialization;
}
public void setInflater(LayoutInflater inflater) {
this.inflater = inflater;
}
private void setEmptyView(@LayoutRes final int emptyResourceId) {
if (mEmptyView == null && emptyResourceId > 0) {
mEmptyId = emptyResourceId;
mEmpty.setLayoutResource(emptyResourceId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mEmpty.setLayoutInflater(inflater);
}
mEmptyView = mEmpty.inflate();
} else {
Log.d(VIEW_LOG_TAG, "unabled to set empty view because the empty has been set");
}
}
private void setEmptyView(@Nullable View mInflatedView) {
if (mInflatedView != null)
mEmptyView = mInflatedView;
}
/**
* Set custom empty view.The view will be shown if the adapter is null or the size of the adapter is zero.
* You can customize it as loading view.
*
* @param emptyResourceId the Resource Id from the empty view
* @param emptyViewPolicy the Resource Id from the empty view
*/
public final void setEmptyView(@LayoutRes int emptyResourceId, final int emptyViewPolicy) {
// mEmptyViewPolicy = emptyViewPolicy;
setEmptyView(emptyResourceId);
setPolicies(emptyViewPolicy, UltimateRecyclerView.STARTWITH_OFFLINE_ITEMS);
mEmpty.setVisibility(View.GONE);
}
public final void setEmptyView(@LayoutRes int emptyResourceId, final int emptyViewPolicy, final int mEmptyViewInitPolicy) {
setEmptyView(emptyResourceId);
setPolicies(emptyViewPolicy, mEmptyViewInitPolicy);
}
public final void setEmptyView(@LayoutRes int emptyResourceId, final int emptyViewPolicy, final emptyViewOnShownListener listener) {
setEmptyView(emptyResourceId);
setPolicies(emptyViewPolicy, UltimateRecyclerView.STARTWITH_OFFLINE_ITEMS);
mEmptyViewListener = listener;
}
public final void setEmptyView(@LayoutRes int emptyResourceId, final int emptyViewPolicy, final int emptyViewInitPolicy, final emptyViewOnShownListener listener) {
setEmptyView(emptyResourceId);
setPolicies(emptyViewPolicy, emptyViewInitPolicy);
mEmptyViewListener = listener;
}
/**
* Show the custom or default empty view
* You can customize it as loading view
*
* @return is the empty shown
*/
public boolean showEmptyView() {
if (mEmpty != null && mEmptyView != null && mAdapter != null) {
if (mAdapter.getEmptyViewPolicy() == EMPTY_CLEAR_ALL || mAdapter.getEmptyViewPolicy() == EMPTY_KEEP_HEADER) {
mEmpty.setVisibility(View.VISIBLE);
if (mEmptyViewListener != null) {
mEmptyViewListener.onEmptyViewShow(mEmptyView);
}
}
return true;
} else {
Log.d(VIEW_LOG_TAG, "it is unable to show empty view");
return false;
}
}
/**
* Hide the custom or default empty view
*/
public void hideEmptyView() {
if (mEmpty != null && mEmptyView != null) {
mEmpty.setVisibility(View.GONE);
} else {
Log.d(VIEW_LOG_TAG, "there is no such empty view");
}
}
public void setLoadMoreView(View mlayoutView) {
if (mLoadMoreView != null) {
Log.d(VIEW_LOG_TAG, "The loading more layout has already been initiated.");
return;
}
if (mlayoutView == null) {
mLoadMoreView = LayoutInflater.from(getContext()).inflate(R.layout.bottom_progressbar, null);
Log.d(VIEW_LOG_TAG, "Layout Resource view is null. This system will use the default loading view instead.");
} else {
mLoadMoreView = mlayoutView;
}
}
/**
* setting up the loading more layout
*
* @param layout the res layout
*/
public void setLoadMoreView(@LayoutRes final int layout) {
if (layout > 0) {
mLoadMoreView = LayoutInflater.from(getContext()).inflate(layout, null);
} else {
Log.d(VIEW_LOG_TAG, "Layout Resource Id is not found for load more view for ulitmaterecyclerview");
}
}
/**
* Show the custom floating button view.
*/
public void showFloatingButtonView() {
if (mFloatingButtonId != 0 && mFloatingButtonView == null) {
mFloatingButtonView = mFloatingButtonViewStub.inflate();
mFloatingButtonView.setVisibility(View.VISIBLE);
} else {
Log.d(VIEW_LOG_TAG, "floating button cannot be inflated because it has inflated already");
}
}
/**
* Add ScrollBar of Recyclerview
*/
protected void setScrollbars() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (mScrollbarsStyle) {
case SCROLLBARS_VERTICAL:
mSwipeRefreshLayout.removeView(mRecyclerView);
View verticalView = inflater.inflate(R.layout.vertical_recycler_view, mSwipeRefreshLayout, true);
mRecyclerView = (RecyclerView) verticalView.findViewById(R.id.ultimate_list);
break;
case SCROLLBARS_HORIZONTAL:
mSwipeRefreshLayout.removeView(mRecyclerView);
View horizontalView = inflater.inflate(R.layout.horizontal_recycler_view, mSwipeRefreshLayout, true);
mRecyclerView = (RecyclerView) horizontalView.findViewById(R.id.ultimate_list);
break;
default:
break;
}
}
protected void initAttrs(AttributeSet attrs) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.UltimateRecyclerview);
try {
mPadding = (int) typedArray.getDimension(R.styleable.UltimateRecyclerview_recyclerviewPadding, -1.1f);
mPaddingTop = (int) typedArray.getDimension(R.styleable.UltimateRecyclerview_recyclerviewPaddingTop, 0.0f);
mPaddingBottom = (int) typedArray.getDimension(R.styleable.UltimateRecyclerview_recyclerviewPaddingBottom, 0.0f);
mPaddingLeft = (int) typedArray.getDimension(R.styleable.UltimateRecyclerview_recyclerviewPaddingLeft, 0.0f);
mPaddingRight = (int) typedArray.getDimension(R.styleable.UltimateRecyclerview_recyclerviewPaddingRight, 0.0f);
mClipToPadding = typedArray.getBoolean(R.styleable.UltimateRecyclerview_recyclerviewClipToPadding, false);
mEmptyId = typedArray.getResourceId(R.styleable.UltimateRecyclerview_recyclerviewEmptyView, 0);
mFloatingButtonId = typedArray.getResourceId(R.styleable.UltimateRecyclerview_recyclerviewFloatingActionView, 0);
mScrollbarsStyle = typedArray.getInt(R.styleable.UltimateRecyclerview_recyclerviewScrollbars, SCROLLBARS_NONE);
int colorList = typedArray.getResourceId(R.styleable.UltimateRecyclerview_recyclerviewDefaultSwipeColor, 0);
if (colorList != 0) {
defaultSwipeToDismissColors = getResources().getIntArray(colorList);
}
//mEmptyViewPolicy = EMPTY_VIEW_POLICY_EMPTY_SHOW;
} finally {
typedArray.recycle();
}
}
private void setObserableScrollListener() {
mRecyclerView.removeOnScrollListener(mOnScrollListener);
mOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
enableShoworHideToolbarAndFloatingButton(recyclerView);
}
};
mRecyclerView.addOnScrollListener(mOnScrollListener);
}
private int[] mlastPositionsStaggeredGridLayout;
private void scroll_load_more_detection(RecyclerView recyclerView) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManagerType == null) {
if (layoutManager instanceof GridLayoutManager) {
layoutManagerType = LAYOUT_MANAGER_TYPE.GRID;
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
layoutManagerType = LAYOUT_MANAGER_TYPE.STAGGERED_GRID;
} else if (layoutManager instanceof LinearLayoutManager) {
layoutManagerType = LAYOUT_MANAGER_TYPE.LINEAR;
} else {
throw new RuntimeException("Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager");
}
}
mTotalItemCount = layoutManager.getItemCount();
mVisibleItemCount = layoutManager.getChildCount();
switch (layoutManagerType) {
case LINEAR:
mFirstVisibleItem = mRecyclerViewHelper.findFirstVisibleItemPosition();
lastVisibleItemPosition = mRecyclerViewHelper.findLastVisibleItemPosition();
break;
case GRID:
if (layoutManager instanceof GridLayoutManager) {
GridLayoutManager ly = (GridLayoutManager) layoutManager;
lastVisibleItemPosition = ly.findLastVisibleItemPosition();
mFirstVisibleItem = ly.findFirstVisibleItemPosition();
}
break;
case STAGGERED_GRID:
if (layoutManager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager sy = (StaggeredGridLayoutManager) layoutManager;
if (mlastPositionsStaggeredGridLayout == null)
mlastPositionsStaggeredGridLayout = new int[sy.getSpanCount()];
sy.findLastVisibleItemPositions(mlastPositionsStaggeredGridLayout);
lastVisibleItemPosition = findMax(mlastPositionsStaggeredGridLayout);
sy.findFirstVisibleItemPositions(mlastPositionsStaggeredGridLayout);
mFirstVisibleItem = findMin(mlastPositionsStaggeredGridLayout);
}
break;
}
if (automaticLoadMoreEnabled) {
if (mTotalItemCount > previousTotal) {
automaticLoadMoreEnabled = false;
previousTotal = mTotalItemCount;
}
}
boolean bottomEdgeHit = (mTotalItemCount - mVisibleItemCount) <= mFirstVisibleItem;
if (bottomEdgeHit) {
if (mIsLoadMoreWidgetEnabled) {
/**auto activate load more**/
if (!automaticLoadMoreEnabled) {
onLoadMoreListener.loadMore(mRecyclerView.getAdapter().getItemCount(), lastVisibleItemPosition);
automaticLoadMoreEnabled = true;
}
}
mAdapter.internalExecuteLoadingView();
previousTotal = mTotalItemCount;
}
}
protected void setDefaultScrollListener() {
mRecyclerView.removeOnScrollListener(mOnScrollListener);
mOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (mHeader != null) {
mTotalYScrolled += dy;
if (isParallaxHeader)
translateHeader(mTotalYScrolled);
}
scroll_load_more_detection(recyclerView);
enableShoworHideToolbarAndFloatingButton(recyclerView);
}
};
mRecyclerView.addOnScrollListener(mOnScrollListener);
}
/**
* If you have used {@link #disableLoadmore()} and want to enable loading more again,you can use this method.
*/
public void reenableLoadmore() {
if (mAdapter != null && mLoadMoreView != null) {
mAdapter.enableLoadMore(true);
}
mIsLoadMoreWidgetEnabled = true;
}
public boolean isLoadMoreEnabled() {
return mIsLoadMoreWidgetEnabled;
}
/**
* Remove loading more scroll listener
*/
public void disableLoadmore() {
mIsLoadMoreWidgetEnabled = false;
if (mAdapter != null && mLoadMoreView != null) {
mAdapter.enableLoadMore(false);
}
}
protected void enableShoworHideToolbarAndFloatingButton(RecyclerView recyclerView) {
if (mCallbacks != null) {
if (getChildCount() > 0) {
int firstVisiblePosition = recyclerView.getChildAdapterPosition(recyclerView.getChildAt(0));
int lastVisiblePosition = recyclerView.getChildAdapterPosition(recyclerView.getChildAt(recyclerView.getChildCount() - 1));
try {
for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++) {
int childHeight = 0;
View child = recyclerView.getChildAt(j);
if (mChildrenHeights.indexOfKey(i) < 0 || (child != null && child.getHeight() != mChildrenHeights.get(i))) {
if (child != null)
childHeight = child.getHeight();
}
mChildrenHeights.put(i, childHeight);
}
} catch (NullPointerException e) {
e.printStackTrace();
//todo: need to solve this issue when the first child is missing from the scroll. Please also see the debug from the RV error.
//todo: 07-01 11:50:36.359 32348-32348/com.marshalchen.ultimaterecyclerview.demo D/RVerror? Attempt to invoke virtual method 'int android.view.View.getHeight()' on a null object reference
URLogs.e(e, "");
}
View firstVisibleChild = recyclerView.getChildAt(0);
if (firstVisibleChild != null) {
if (mPrevFirstVisiblePosition < firstVisiblePosition) {
// scroll down
int skippedChildrenHeight = 0;
if (firstVisiblePosition - mPrevFirstVisiblePosition != 1) {
for (int i = firstVisiblePosition - 1; i > mPrevFirstVisiblePosition; i--) {
if (0 < mChildrenHeights.indexOfKey(i)) {
skippedChildrenHeight += mChildrenHeights.get(i);
} else {
// Approximate each item's height to the first visible child.
// It may be incorrect, but without this, scrollY will be broken
// when scrolling from the bottom.
skippedChildrenHeight += firstVisibleChild.getHeight();
}
}
}
mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight + skippedChildrenHeight;
mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight();
} else if (firstVisiblePosition < mPrevFirstVisiblePosition) {
// scroll up
int skippedChildrenHeight = 0;
if (mPrevFirstVisiblePosition - firstVisiblePosition != 1) {
for (int i = mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--) {
if (0 < mChildrenHeights.indexOfKey(i)) {
skippedChildrenHeight += mChildrenHeights.get(i);
} else {
// Approximate each item's height to the first visible child.
// It may be incorrect, but without this, scrollY will be broken
// when scrolling from the bottom.
skippedChildrenHeight += firstVisibleChild.getHeight();
}
}
}
mPrevScrolledChildrenHeight -= firstVisibleChild.getHeight() + skippedChildrenHeight;
mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight();
} else if (firstVisiblePosition == 0) {
mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight();
mPrevScrolledChildrenHeight = 0;
}
if (mPrevFirstVisibleChildHeight < 0) {
mPrevFirstVisibleChildHeight = 0;
}
mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.getTop();
mPrevFirstVisiblePosition = firstVisiblePosition;
mCallbacks.onScrollChanged(mScrollY, mFirstScroll, mDragging);
if (mPrevScrollY < mScrollY) {
//down
if (mFirstScroll) { // first scroll down , mPrevScrollY == 0, reach here.
mFirstScroll = false;
mObservableScrollState = ObservableScrollState.STOP;
}
mObservableScrollState = ObservableScrollState.UP;
} else if (mScrollY < mPrevScrollY) {
//up
mObservableScrollState = ObservableScrollState.DOWN;
} else {
mObservableScrollState = ObservableScrollState.STOP;
}
if (mFirstScroll) {
mFirstScroll = false;
}
mPrevScrollY = mScrollY;
}
}
}
}
/**
* Set a listener that will be notified of any changes in scroll state or position.
*
* @param customOnScrollListener to set or null to clear
* @deprecated Use {@link #addOnScrollListener(RecyclerView.OnScrollListener)} and
* {@link #removeOnScrollListener(RecyclerView.OnScrollListener)}
*/
public void setOnScrollListener(RecyclerView.OnScrollListener customOnScrollListener) {
mRecyclerView.setOnScrollListener(customOnScrollListener);
}
public void addOnScrollListener(RecyclerView.OnScrollListener customOnScrollListener) {
mRecyclerView.addOnScrollListener(customOnScrollListener);
}
public void removeOnScrollListener(RecyclerView.OnScrollListener customOnScrollListener) {
mRecyclerView.removeOnScrollListener(customOnScrollListener);
}
public void addItemDividerDecoration(Context context) {
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST);
mRecyclerView.addItemDecoration(itemDecoration);
}
/**
* Swaps the current adapter with the provided one. It is similar to
* {@link #setAdapter(UltimateViewAdapter)} but assumes existing adapter and the new adapter uses the same
* ViewHolder and does not clear the RecycledViewPool.
* Note that it still calls onAdapterChanged callbacks.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing Views. If adapters have stable ids and/or you want to animate the disappearing views, you may prefer to set this to false.
*/
public void swapAdapter(UltimateViewAdapter adapter, boolean removeAndRecycleExistingViews) {
mRecyclerView.swapAdapter(adapter, removeAndRecycleExistingViews);
setAdapterInternal(adapter);
}
public void setAdapter(UltimateViewAdapter adapter) {
mRecyclerView.setAdapter(adapter);
setAdapterInternal(adapter);
}
/**
* Add an {@link RecyclerView.ItemDecoration} to this RecyclerView. Item decorations can affect both measurement and drawing of individual item views. Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.
*
* @param itemDecoration Decoration to add
*/
public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
mRecyclerView.addItemDecoration(itemDecoration);
}
/**
* Add an {@link RecyclerView.ItemDecoration} to this RecyclerView. Item decorations can affect both measurement and drawing of individual item views.
*
Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.
*
* @param itemDecoration Decoration to add
* @param index Position in the decoration chain to insert this decoration at. If this value is negative the decoration will be added at the end.
*/
public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration, int index) {
mRecyclerView.addItemDecoration(itemDecoration, index);
}
/**
* Sets the {@link RecyclerView.ItemAnimator} that will handle animations involving changes
* to the items in this RecyclerView. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}. Whether item animations are enabled for the RecyclerView depends on the ItemAnimator and whether
* the LayoutManager {@link RecyclerView.LayoutManager#supportsPredictiveItemAnimations()
* supports item animations}.
*
* @param animator The ItemAnimator being set. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
*/
public void setItemAnimator(RecyclerView.ItemAnimator animator) {
mRecyclerView.setItemAnimator(animator);
}
/**
* Gets the current ItemAnimator for this RecyclerView. A null return value
* indicates that there is no animator and that item changes will happen without
* any animations. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}.
*
* @return ItemAnimator The current ItemAnimator. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
*/
public RecyclerView.ItemAnimator getItemAnimator() {
return mRecyclerView.getItemAnimator();
}
/**
* Set the listener when refresh is triggered and enable the SwipeRefreshLayout
*
* @param listener SwipeRefreshLayout
*/
public void setDefaultOnRefreshListener(SwipeRefreshLayout.OnRefreshListener listener) {
mSwipeRefreshLayout.setEnabled(true);
if (defaultSwipeToDismissColors != null && defaultSwipeToDismissColors.length > 0) {
mSwipeRefreshLayout.setColorSchemeColors(defaultSwipeToDismissColors);
} else {
mSwipeRefreshLayout.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
mSwipeRefreshLayout.setOnRefreshListener(listener);
}
/**
* Set the color resources used in the progress animation from color resources. The first color will also be the color of the bar that grows in response to a user swipe gesture.
*
* @param colors colors in array
*/
public void setDefaultSwipeToRefreshColorScheme(int... colors) {
mSwipeRefreshLayout.setColorSchemeColors(colors);
}
/**
* Set the load more listener of recyclerview
*
* @param onLoadMoreListener load listen
*/
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
/**
* Set the layout manager to the recycler
*
* @param manager lm
*/
public void setLayoutManager(RecyclerView.LayoutManager manager) {
mRecyclerView.setLayoutManager(manager);
}
/**
* Get the adapter of UltimateRecyclerview
*
* @return ad
*/
public RecyclerView.Adapter getAdapter() {
return mRecyclerView.getAdapter();
}
/**
* Set a UltimateViewAdapter or the subclass of UltimateViewAdapter to the recyclerview
*
* @param adapter the adapter in normal
*/
private void setAdapterInternal(UltimateViewAdapter adapter) {
mAdapter = adapter;
if (mSwipeRefreshLayout != null)
mSwipeRefreshLayout.setRefreshing(false);
if (mAdapter != null)
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
super.onItemRangeChanged(positionStart, itemCount);
updateHelperDisplays();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
updateHelperDisplays();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
updateHelperDisplays();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount);
updateHelperDisplays();
}
@Override
public void onChanged() {
super.onChanged();
updateHelperDisplays();
}
});
mRecyclerViewHelper = RecyclerViewPositionHelper.createHelper(mRecyclerView);
mAdapter.setEmptyViewPolicy(policy_empty);
mAdapter.setEmptyViewOnInitPolicy(policy_init);
if (mAdapter.getAdapterItemCount() == 0 && policy_init == UltimateRecyclerView.STARTWITH_OFFLINE_ITEMS) {
showEmptyView();
}
if (policy_init == UltimateRecyclerView.STARTWITH_ONLINE_ITEMS) {
hideEmptyView();
}
if (mAdapter.getCustomLoadMoreView() == null && mLoadMoreView != null) {
mAdapter.setCustomLoadMoreView(mLoadMoreView);
mAdapter.enableLoadMore(true);
mAdapter.notifyDataSetChanged();
mIsLoadMoreWidgetEnabled = true;
}
if (mHeader != null) {
mAdapter.setCustomHeaderView(mHeader);
//getLayoutManager().ignoreView(mHeader);
}
}
private void updateHelperDisplays() {
automaticLoadMoreEnabled = false;
if (mSwipeRefreshLayout != null)
mSwipeRefreshLayout.setRefreshing(false);
if (mAdapter == null)
return;
/**
* fixed by jjHesk
* + empty layout is NONE
* + getItemCount is zero
*/
if (!isFirstLoadingOnlineAdapter) {
isFirstLoadingOnlineAdapter = true;
if (mAdapter.getAdapterItemCount() == 0) {
mEmpty.setVisibility(mEmptyView == null ? View.VISIBLE : View.GONE);
} else if (mEmptyId != 0) {
implementLoadMorebehavior();
mEmpty.setVisibility(View.GONE);
}
} else {
//isFirstLoadingOnlineAdapter = false;
setRefreshing(false);
implementLoadMorebehavior();
}
}
private void implementLoadMorebehavior() {
if (mAdapter.getCustomLoadMoreView() != null) {
if (mAdapter.enableLoadMore()) {
mAdapter.getCustomLoadMoreView().setVisibility(View.VISIBLE);
} else {
mAdapter.getCustomLoadMoreView().setVisibility(View.GONE);
}
}
}
public void setHasFixedSize(boolean hasFixedSize) {
mRecyclerView.setHasFixedSize(hasFixedSize);
}
/**
* Notify the widget that refresh state has changed. Do not call this when refresh is triggered by a swipe gesture.
*
* @param refreshing enable the refresh loading icon
*/
public void setRefreshing(boolean refreshing) {
if (mSwipeRefreshLayout != null)
mSwipeRefreshLayout.setRefreshing(refreshing);
}
/**
* Enable or disable the SwipeRefreshLayout.
* Default is false
*
* @param isSwipeRefresh is now operating in refresh
*/
public void enableDefaultSwipeRefresh(boolean isSwipeRefresh) {
if (mSwipeRefreshLayout != null)
mSwipeRefreshLayout.setEnabled(isSwipeRefresh);
}
public interface OnLoadMoreListener {
void loadMore(int itemsCount, final int maxLastVisiblePosition);
}
public enum LAYOUT_MANAGER_TYPE {
LINEAR,
GRID,
STAGGERED_GRID,
PUZZLE,
}
private int findMax(int[] lastPositions) {
int max = Integer.MIN_VALUE;
for (int value : lastPositions) {
if (value > max)
max = value;
}
return max;
}
private int findMin(int[] lastPositions) {
int min = Integer.MAX_VALUE;
for (int value : lastPositions) {
if (value != RecyclerView.NO_POSITION && value < min)
min = value;
}
return min;
}
/**
* allow resource layout id to be introduced
*
* @param mLayout res id
*/
public void setParallaxHeader(@LayoutRes int mLayout) {
View h_layout = LayoutInflater.from(getContext()).inflate(mLayout, null);
setParallaxHeader(h_layout);
}
/**
* Set the parallax header of the recyclerview
*
* @param header the view
*/
public void setParallaxHeader(View header) {
mHeader = new CustomRelativeWrapper(header.getContext());
mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
isParallaxHeader = true;
}
/**
* Set the normal header of the recyclerview
*
* @param header na
*/
public void setNormalHeader(View header) {
setParallaxHeader(header);
isParallaxHeader = false;
}
/**
* Set the on scroll method of parallax header
*
* @param parallaxScroll na
*/
public void setOnParallaxScroll(OnParallaxScroll parallaxScroll) {
mParallaxScroll = parallaxScroll;
mParallaxScroll.onParallaxScroll(0, 0, mHeader);
}
private float mScrollMultiplier = 0.5f;
/**
* Translates the adapter in Y
*
* @param of offset in px
*/
public void translateHeader(float of) {
float ofCalculated = of * mScrollMultiplier;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && of < mHeader.getHeight()) {
mHeader.setTranslationY(ofCalculated);
} else if (of < mHeader.getHeight()) {
TranslateAnimation anim = new TranslateAnimation(0, 0, ofCalculated, ofCalculated);
anim.setFillAfter(true);
anim.setDuration(0);
mHeader.startAnimation(anim);
}
mHeader.setClipY(Math.round(ofCalculated));
if (mParallaxScroll != null) {
final RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForAdapterPosition(0);
float left;
if (holder != null) {
left = Math.min(1, ((ofCalculated) / (mHeader.getHeight() * mScrollMultiplier)));
}else {
left = 1;
}
mParallaxScroll.onParallaxScroll(left, of, mHeader);
}
}
/**
* Set parallax scroll multiplier.
*
* @param mul The multiplier
*/
public void setScrollMultiplier(float mul) {
this.mScrollMultiplier = mul;
}
/**
* Get the current parallax scroll multiplier.
*
*/
public float getScrollMultiplier() {
return this.mScrollMultiplier;
}
public interface OnParallaxScroll {
void onParallaxScroll(float percentage, float offset, View parallax);
}
/**
* Custom layout for the Parallax Header.
*/
public static class CustomRelativeWrapper extends RelativeLayout {
private int mOffset;
public CustomRelativeWrapper(Context context) {
super(context);
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (isParallaxHeader)
canvas.clipRect(new Rect(getLeft(), getTop(), getRight(), getBottom() + mOffset));
super.dispatchDraw(canvas);
}
public void setClipY(int offset) {
mOffset = offset;
invalidate();
}
}
/**
* the observable scroll view call backs
*
* @param listener listener to set
*/
public void setScrollViewCallbacks(ObservableScrollViewCallbacks listener) {
mCallbacks = listener;
}
public void setItemViewCacheSize(final int off_screen_items) {
mRecyclerView.setItemViewCacheSize(off_screen_items);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedStateScrolling ss = (SavedStateScrolling) state;
mPrevFirstVisiblePosition = ss.prevFirstVisiblePosition;
mPrevFirstVisibleChildHeight = ss.prevFirstVisibleChildHeight;
mPrevScrolledChildrenHeight = ss.prevScrolledChildrenHeight;
mPrevScrollY = ss.prevScrollY;
mScrollY = ss.scrollY;
mChildrenHeights = ss.childrenHeights;
RecyclerView.LayoutManager layoutManager = getLayoutManager();
/**
* enhanced and store the previous scroll position
*/
if (layoutManager != null) {
int count = layoutManager.getChildCount();
if (mPrevScrollY != RecyclerView.NO_POSITION && mPrevScrollY < count) {
layoutManager.scrollToPosition(mPrevScrollY);
}
}
super.onRestoreInstanceState(ss.getSuperState());
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedStateScrolling ss = new SavedStateScrolling(superState);
ss.prevFirstVisiblePosition = mPrevFirstVisiblePosition;
ss.prevFirstVisibleChildHeight = mPrevFirstVisibleChildHeight;
ss.prevScrolledChildrenHeight = mPrevScrolledChildrenHeight;
ss.prevScrollY = mPrevScrollY;
ss.scrollY = mScrollY;
ss.childrenHeights = mChildrenHeights;
return ss;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mCallbacks != null) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mFirstScroll = mDragging = true;
mCallbacks.onDownMotionEvent();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIntercepted = false;
mDragging = false;
mCallbacks.onUpOrCancelMotionEvent(mObservableScrollState);
break;
}
}
return super.onInterceptTouchEvent(ev);
}
@Override
public void setTouchInterceptionViewGroup(ViewGroup viewGroup) {
mTouchInterceptionViewGroup = viewGroup;
setObserableScrollListener();
}
@Override
public void scrollVerticallyTo(int y) {
URLogs.d("vertically");
View firstVisibleChild = getChildAt(0);
if (firstVisibleChild != null) {
int baseHeight = firstVisibleChild.getHeight();
int position = y / baseHeight;
scrollVerticallyToPosition(position);
}
}
public void scrollVerticallyToPosition(int position) {
RecyclerView.LayoutManager lm = getLayoutManager();
if (lm != null && lm instanceof LinearLayoutManager) {
((LinearLayoutManager) lm).scrollToPositionWithOffset(position, 0);
} else {
lm.scrollToPosition(position);
}
}
@Override
public int getCurrentScrollY() {
return mScrollY;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
URLogs.d("ev---" + ev);
if (mCallbacks != null) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIntercepted = false;
mDragging = false;
mCallbacks.onUpOrCancelMotionEvent(mObservableScrollState);
break;
case MotionEvent.ACTION_MOVE:
if (mPrevMoveEvent == null) {
mPrevMoveEvent = ev;
}
float diffY = ev.getY() - mPrevMoveEvent.getY();
mPrevMoveEvent = MotionEvent.obtainNoHistory(ev);
if (getCurrentScrollY() - diffY <= 0) {
// Can't scroll anymore.
if (mIntercepted) {
// Already dispatched ACTION_DOWN event to parents, so stop here.
return false;
}
// Apps can set the interception target other than the direct parent.
final ViewGroup parent;
if (mTouchInterceptionViewGroup == null) {
parent = (ViewGroup) getParent();
} else {
parent = mTouchInterceptionViewGroup;
}
// Get offset to parents. If the parent is not the direct parent,
// we should aggregate offsets from all of the parents.
float offsetX = 0;
float offsetY = 0;
for (View v = this; v != null && v != parent; v = (View) v.getParent()) {
offsetX += v.getLeft() - v.getScrollX();
offsetY += v.getTop() - v.getScrollY();
}
final MotionEvent event = MotionEvent.obtainNoHistory(ev);
event.offsetLocation(offsetX, offsetY);
if (parent.onInterceptTouchEvent(event)) {
mIntercepted = true;
// If the parent wants to intercept ACTION_MOVE events,
// we pass ACTION_DOWN event to the parent
// as if these touch events just have began now.
event.setAction(MotionEvent.ACTION_DOWN);
// Return this onTouchEvent() first and set ACTION_DOWN event for parent
// to the queue, to keep events sequence.
post(new Runnable() {
@Override
public void run() {
parent.dispatchTouchEvent(event);
}
});
return false;
}
// Even when this can't be scrolled anymore,
// simply returning false here may cause subView's click,
// so delegate it to super.
return super.onTouchEvent(ev);
}
break;
}
}
return super.onTouchEvent(ev);
}
public boolean toolbarIsShown(Toolbar mToolbar) {
return ViewCompat.getTranslationY(mToolbar) == 0;
}
public boolean toolbarIsHidden(Toolbar mToolbar) {
return ViewCompat.getTranslationY(mToolbar) == -mToolbar.getHeight();
}
@Deprecated
public void showToolbarAndFAB(Toolbar mToolbar, UltimateRecyclerView ultimateRecyclerView, int screenHeight) {
showToolbar(mToolbar, ultimateRecyclerView, screenHeight);
showDefaultFloatingActionButton();
}
@Deprecated
public void hideToolbarAndFAB(Toolbar mToolbar, UltimateRecyclerView ultimateRecyclerView, int screenHeight) {
hideToolbar(mToolbar, ultimateRecyclerView, screenHeight);
hideDefaultFloatingActionButton();
}
public void showToolbar(Toolbar mToolbar, UltimateRecyclerView ultimateRecyclerView, int screenHeight) {
moveToolbar(mToolbar, ultimateRecyclerView, screenHeight, 0);
}
public void hideToolbar(Toolbar mToolbar, UltimateRecyclerView ultimateRecyclerView, int screenHeight) {
moveToolbar(mToolbar, ultimateRecyclerView, screenHeight, -mToolbar.getHeight());
}
public void showView(View mView, UltimateRecyclerView ultimateRecyclerView, int screenHeight) {
moveView(mView, ultimateRecyclerView, screenHeight, 0);
}
public void hideView(View mView, UltimateRecyclerView ultimateRecyclerView, int screenHeight) {
moveView(mView, ultimateRecyclerView, screenHeight, -mView.getHeight());
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void moveToolbar(final Toolbar mToolbar, final UltimateRecyclerView ultimateRecyclerView, final int screenheight, float toTranslationY) {
if (ViewCompat.getTranslationY(mToolbar) == toTranslationY) {
return;
}
ValueAnimator animator = ValueAnimator.ofFloat(ViewCompat.getTranslationY(mToolbar), toTranslationY).setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float translationY = (float) animation.getAnimatedValue();
ViewCompat.setTranslationY(mToolbar, translationY);
ViewCompat.setTranslationY((View) ultimateRecyclerView, translationY);
// FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) ((View) ultimateRecyclerView).getLayoutParams();
MarginLayoutParams layoutParams = (MarginLayoutParams) ((View) ultimateRecyclerView).getLayoutParams();
layoutParams.height = (int) -translationY + screenheight - layoutParams.topMargin;
((View) ultimateRecyclerView).requestLayout();
}
});
animator.start();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void moveView(final View mView, final UltimateRecyclerView ultimateRecyclerView, final int screenheight, float toTranslationY) {
if (ViewCompat.getTranslationY(mView) == toTranslationY) {
return;
}
ValueAnimator animator = ValueAnimator.ofFloat(ViewCompat.getTranslationY(mView), toTranslationY).setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float translationY = (float) animation.getAnimatedValue();
ViewCompat.setTranslationY(mView, translationY);
ViewCompat.setTranslationY((View) ultimateRecyclerView, translationY);
// FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) ((View) ultimateRecyclerView).getLayoutParams();
MarginLayoutParams layoutParams = (MarginLayoutParams) ((View) ultimateRecyclerView).getLayoutParams();
layoutParams.height = (int) -translationY + screenheight - layoutParams.topMargin;
((View) ultimateRecyclerView).requestLayout();
}
});
animator.start();
}
public FloatingActionButton getDefaultFloatingActionButton() {
return defaultFloatingActionButton;
}
public void setDefaultFloatingActionButton(FloatingActionButton defaultFloatingActionButton) {
this.defaultFloatingActionButton = defaultFloatingActionButton;
}
public View getCustomFloatingActionView() {
return mFloatingButtonView;
}
// public void setCustomFloatingActionView(View customFloatingActionView) {
// this.floatingActionMenu = floatingActionMenu;
// }
public void showFloatingActionMenu() {
if (mFloatingButtonView != null)
((FloatingActionsMenu) mFloatingButtonView).hide(false);
}
public void hideFloatingActionMenu() {
if (mFloatingButtonView != null) ((FloatingActionsMenu) mFloatingButtonView).hide(true);
}
public void showFloatingActionButton() {
if (mFloatingButtonView != null)
((FloatingActionButton) mFloatingButtonView).hide(false);
}
public void hideFloatingActionButton() {
if (mFloatingButtonView != null) ((FloatingActionButton) mFloatingButtonView).hide(true);
}
public void showDefaultFloatingActionButton() {
defaultFloatingActionButton.hide(false);
}
public void hideDefaultFloatingActionButton() {
defaultFloatingActionButton.hide(true);
}
public void displayCustomFloatingActionView(boolean b) {
if (mFloatingButtonView != null)
mFloatingButtonView.setVisibility(b ? VISIBLE : INVISIBLE);
}
public void displayDefaultFloatingActionButton(boolean b) {
defaultFloatingActionButton.setVisibility(b ? VISIBLE : INVISIBLE);
}
public void removeItemDecoration(RecyclerView.ItemDecoration decoration) {
mRecyclerView.removeItemDecoration(decoration);
}
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
mRecyclerView.addOnItemTouchListener(listener);
}
public void removeOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
mRecyclerView.removeOnItemTouchListener(listener);
}
public RecyclerView.LayoutManager getLayoutManager() {
return mRecyclerView.getLayoutManager();
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/UltimateRecyclerviewViewHolder.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.content.Context;
import android.content.res.Resources;
import androidx.recyclerview.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import com.marshalchen.ultimaterecyclerview.itemTouchHelper.ItemTouchHelperViewHolder;
import com.marshalchen.ultimaterecyclerview.swipe.SwipeLayout;
/**
* Created by MarshalChen on 15-6-2.
* adding by Hesk 2016-2-29
*/
public class UltimateRecyclerviewViewHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
private SparseArray> mSparseSparseArrayView
= new SparseArray>();
private View mView;
private T mObject;
public SwipeLayout swipeLayout = null;
public SwipeLayout.OnLayout onLayoutListener = null;
public SwipeLayout.SwipeListener swipeMemory = null;
public int position = -1;
public UltimateRecyclerviewViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.recyclerview_swipe);
mView = itemView;
}
/**
* Method called when we need to update the view hold by this class.
*
* @param object the object subject of this update
*/
public void onBindView(Object object) {
mObject = (T) object;
updateView(mView.getContext(), mObject);
}
/**
* Get the last object set to this viewholder
*
* @return the type
*/
public T getObject() {
return mObject;
}
/**
* Method called when we need to update the view hold by this class.
*
* @param context context of the root view
* @param object the object subject of this update
*/
protected void updateView(Context context, T object) {
}
/**
* Get the root view for the viewholder (the one passed into the constructor)
*
* @return The viewholder's root view, or null if it has no layout.
*/
public View getView() {
return mView;
}
/**
* Returns the context the view is running in, through which it can
* access the current theme, resources, etc.
*
* @return The view's Context.
*/
public Context getContext() {
return mView.getContext();
}
/**
* Returns the resources associated with this view.
*
* @return Resources object.
*/
public Resources getResources() {
return mView.getResources();
}
@Override
public void onItemSelected() {
}
@Override
public void onItemClear() {
}
/**
* Called when a view created by the adapter has been recycled.
*/
public void onViewRecycled() {
}
/**
* Called when a view created by the adapter has been attached to a window.
*/
public void onViewAttachedToWindow() {
}
/**
* Called when a view created by the adapter has been detached from its window.
*/
public void onViewDetachedFromWindow() {
}
/**
* Determine if a click listener should be automatically added to the view of this view holder
*
* @return true you want to have this view clickable
*/
public boolean isClickable() {
return false;
}
/**
* Determine if a long click listener should be automatically added to the view of this view holder
*
* @return true you want to have this view clickable
*/
public boolean isLongClickable() {
return false;
}
/**
* Look for a child view with the given id. If this view has the given
* id, return this view.
* The method is efficient, if you had already called it, it will be faster than a normal
* "findViewById" thanks to a cache system
* @param id The id to search for.
* @param the type of view
* @return The view that has the given id in the hierarchy or null
*/
public T findViewByIdEfficient(int id) {
return (T) findViewByIdEfficient(0, id);
}
/**
* Look for a child view of the parent view id with the given id. If this view has the given
* id, return this view.
* The method is efficient, if you had already called it, it will be faster than a normal
* "findViewById" thanks to a cache system
* @param parentId the parent id
* @param id The id to search for.
* @param type of object
* @return The view that has the given id in the hierarchy or null
*/
public T findViewByIdEfficient(int parentId, int id) {
View viewRetrieve = retrieveFromCache(parentId, id);
if (viewRetrieve == null) {
viewRetrieve = findViewById(parentId, id);
if (viewRetrieve != null) {
storeView(parentId, id, viewRetrieve);
}
}
return (T) viewRetrieve;
}
private void storeView(int parentId, int id, View viewRetrieve) {
SparseArray sparseArrayViewsParent = mSparseSparseArrayView.get(parentId);
if (sparseArrayViewsParent == null) {
sparseArrayViewsParent = new SparseArray();
mSparseSparseArrayView.put(parentId, sparseArrayViewsParent);
}
sparseArrayViewsParent.put(id, viewRetrieve);
}
private View findViewById(int parentId, int id) {
if (parentId == 0) {
return mView.findViewById(id);
} else {
View parent = findViewByIdEfficient(parentId);
if (parent != null) {
return parent.findViewById(id);
} else {
return null;
}
}
}
private View retrieveFromCache(int parentId, int id) {
SparseArray sparseArrayViewsParent = mSparseSparseArrayView.get(parentId);
if (sparseArrayViewsParent != null) {
View viewRetrieve = sparseArrayViewsParent.get(id);
if (viewRetrieve == null) {
// dead reference
sparseArrayViewsParent.remove(id);
} else {
return viewRetrieve;
}
}
if (parentId == 0) {
return retrieveFromCache(id);
} else {
return null;
}
}
private View retrieveFromCache(int id) {
for (int i = 0; i < mSparseSparseArrayView.size(); i++) {
int parentId = mSparseSparseArrayView.keyAt(i);
if (parentId != 0) {
View viewRetrieve = retrieveFromCache(parentId, id);
if (viewRetrieve != null) {
return viewRetrieve;
}
}
}
return null;
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/UltimateViewAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.itemTouchHelper.ItemTouchHelperAdapter;
import com.marshalchen.ultimaterecyclerview.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* An abstract adapter which can be extended for Recyclerview
*/
public abstract class UltimateViewAdapter extends RecyclerView.Adapter implements StickyRecyclerHeadersAdapter, ItemTouchHelperAdapter {
protected Handler timer = new Handler();
protected UltimateRecyclerView.CustomRelativeWrapper customHeaderView = null;
protected View customLoadMoreView = null;
protected View customLoadMoreItemView = null;
private boolean customHeader = false;
/**
* this watches how many times does this loading more triggered
*/
private int loadmoresetingswatch = 0;
public boolean enabled_custom_load_more_view = false;
protected int mEmptyViewPolicy;
protected int mEmptyViewOnInitPolicy;
/**
* Lock used to modify the content of list. Any write operation
* performed on the array should be synchronized on this lock.
*/
protected final Object mLock = new Object();
/**
* Set the header view of the adapter.
*
* @param customHeaderView na
*/
public void setCustomHeaderView(UltimateRecyclerView.CustomRelativeWrapper customHeaderView) {
this.customHeaderView = customHeaderView;
customHeader = true;
}
public UltimateRecyclerView.CustomRelativeWrapper getCustomHeaderView() {
return customHeaderView;
}
public boolean hasHeaderView() {
return customHeader;
}
/**
* Using a custom LoadMoreView
*
* @param customview the inflated view
*/
public final void setCustomLoadMoreView(@Nullable View customview) {
customLoadMoreView = customview;
}
public final View getCustomLoadMoreView() {
return customLoadMoreView;
}
/**
* the get function to get load more
*
* @return determine this is a get function
*/
public final boolean enableLoadMore() {
return enabled_custom_load_more_view;
}
private class delayEnableLoadmore implements Runnable {
private boolean enabled;
public delayEnableLoadmore(final boolean b) {
enabled = b;
}
@Override
public void run() {
if (!enabled && loadmoresetingswatch > 0 && customLoadMoreView != null) {
final int displaySize = getItemCount();
final int dataSize = getAdapterItemCount();
if (dataSize > 0 && customLoadMoreItemView != null) {
notifyItemRemoved(displaySize - 1);
}
detectDispatchLoadMoreDisplay(getAdapterItemCount(), getItemCount());
}
enabled_custom_load_more_view = enabled;
if (enabled && customLoadMoreView == null) {
enabled_custom_load_more_view = false;
}
if (enabled) {
revealDispatchLoadMoreView();
}
}
}
public delayEnableLoadmore cbloadmore;
/**
* as the set function to switching load more feature
*
* @param b bool
*/
public final void enableLoadMore(final boolean b) {
cbloadmore = new delayEnableLoadmore(b);
}
public final void internalExecuteLoadingView() {
if (cbloadmore != null) {
timer.post(cbloadmore);
loadmoresetingswatch++;
cbloadmore = null;
}
}
/**
* Called by RecyclerView when it stops observing this Adapter.
*
* @param recyclerView The RecyclerView instance which stopped observing this adapter.
* @see #onAttachedToRecyclerView(RecyclerView)
*/
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
timer.removeCallbacks(cbloadmore);
}
public final void setEmptyViewPolicy(final int policy) {
mEmptyViewPolicy = policy;
}
public final void setEmptyViewOnInitPolicy(final int policy) {
mEmptyViewOnInitPolicy = policy;
}
public final int getEmptyViewPolicy() {
return mEmptyViewPolicy;
}
public final int getEmptyViewInitPolicy() {
return mEmptyViewOnInitPolicy;
}
/**
* the basic view holder creation
*
* @param parent coming from the bottom api
* @param viewType coming the bottom api as well
* @return expected a typed view holder
*/
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPES.FOOTER) {
VH viewHolder = newFooterHolder(customLoadMoreView);
/**
* this is only for the first time rendering of the adapter
*/
customLoadMoreItemView = viewHolder.itemView;
if (getAdapterItemCount() == 0) {
removeDispatchLoadMoreView();
}
if (enabled_custom_load_more_view && getAdapterItemCount() > 0) {
revealDispatchLoadMoreView();
}
return viewHolder;
} else if (viewType == VIEW_TYPES.HEADER) {
return newHeaderHolder(customHeaderView);
} else if (viewType == VIEW_TYPES.ADVIEW) {
return getAdViewHolder(customHeaderView);
} else if (viewType == VIEW_TYPES.CUSTOMVIEW) {
return newCustomViewHolder(customHeaderView);
} else if (viewType == VIEW_TYPES.NOVIEW) {
return getNoViewHolder(customHeaderView);
}
return onCreateViewHolder(parent);
}
/**
* requirement: ADVIEW
*
* @param view v
* @return holder for this ADVIEW
*/
public VH getAdViewHolder(View view) {
return null;
}
/**
* requirement: CUSTOMVIEW
*
* @param view v
* @return v
*/
public VH newCustomViewHolder(View view) {
return null;
}
/**
* requirement: NOVIEW
*
* @param view v
* @return v
*/
public VH getNoViewHolder(View view) {
return null;
}
/**
* requirement: FOOTER, HEADER. it does not bind and need to do that in the header binding
*
* @param view with no binding view of nothing
* @return v
*/
public abstract VH newFooterHolder(View view);
public abstract VH newHeaderHolder(View view);
/**
* for all NORMAL type holder
*
* @param parent view group parent
* @return vh
*/
public abstract VH onCreateViewHolder(ViewGroup parent);
@Override
public int getItemViewType(int position) {
// int k = getAdapterItemCount();
if (getAdapterItemCount() == 0) {
if (position == 0) {
if (enableLoadMore() && hasHeaderView()) {
//both
return VIEW_TYPES.FOOTER;
} else if (!enableLoadMore() && hasHeaderView()) {
//only header
return VIEW_TYPES.HEADER;
} else if (enableLoadMore() && !hasHeaderView()) {
//only load more
return VIEW_TYPES.FOOTER;
} else {
return VIEW_TYPES.NOVIEW;
}
} else if (position == 1) {
if (enableLoadMore() && hasHeaderView()) {
//both
return VIEW_TYPES.FOOTER;
} else if (!enableLoadMore() && hasHeaderView()) {
//only header
return VIEW_TYPES.NOVIEW;
} else if (enableLoadMore() && !hasHeaderView()) {
//only load more
return VIEW_TYPES.NOVIEW;
} else {
return VIEW_TYPES.NOVIEW;
}
} else {
return VIEW_TYPES.NOVIEW;
}
} else if (getAdapterItemCount() > 0) {
int last_item = getItemCount() - 1;
if (position == last_item && enableLoadMore()) {
return VIEW_TYPES.FOOTER;
} else if (position == 0 && hasHeaderView()) {
return VIEW_TYPES.HEADER;
} else if (isOnCustomView(position)) {
return VIEW_TYPES.ADVIEW;
} else if (isOnAdView(position)) {
return VIEW_TYPES.ADVIEW;
} else {
return VIEW_TYPES.NORMAL;
}
} else {
return VIEW_TYPES.NORMAL;
}
}
protected boolean isOnCustomView(final int pos) {
return false;
}
protected boolean isOnAdView(final int pos) {
return false;
}
/**
* retrieve the amount of the total items in the urv for display that will be including all data items as well as the decorative items
*
* @return the int
*/
@Override
public int getItemCount() {
return getAdapterItemCount() + totalAdditionalItems();
}
public int getAdditionalItems() {
return totalAdditionalItems();
}
protected int totalAdditionalItems() {
int offset = 0;
if (hasHeaderView()) offset++;
if (enableLoadMore()) offset++;
return offset;
}
/**
* Returns the number of items in the adapter bound to the parent RecyclerView.
*
* @return The number of data items in the bound adapter
*/
public abstract int getAdapterItemCount();
public final void toggleSelection(int pos) {
notifyItemChanged(pos);
}
public final void clearSelection(int pos) {
notifyItemChanged(pos);
}
public final void setSelected(int pos) {
notifyItemChanged(pos);
}
/**
* Swap the item of list
*
* @param list data list
* @param from position from
* @param to position to
*/
public void swapPositions(List> list, int from, int to) {
if (hasHeaderView()) {
from--;
to--;
}
if (enableLoadMore() && to == getItemCount() - 1) return;
if (hasHeaderView() && to == 0) return;
if (hasHeaderView() && from == 0) return;
if (enableLoadMore() && from == getItemCount() - 1) return;
Collections.swap(list, from, to);
}
/**
* Insert a item to the list of the adapter
*
* @param list data list
* @param object object T
* @param position position
* @param in T
*/
public final void insertInternal(List list, T object, final int position) {
list.add(position, object);
int g = position;
if (hasHeaderView()) g++;
notifyItemInserted(g);
}
public final void insertFirstInternal(List list, T item) {
insertInternal(list, item, 0);
}
public final void insertLastInternal(List list, T item) {
insertInternal(list, item, getAdapterItemCount());
}
/**
* insert the new item list after the whole list
*
* @param insert_data new list
* @param original_list original copy
* @param the type
*/
public final void insertInternal(List insert_data, List original_list) {
try {
Iterator id = insert_data.iterator();
int g = getItemCount();
// if (hasHeaderView()) g--;
if (enableLoadMore()) g--;
final int start = g;
synchronized (mLock) {
while (id.hasNext()) {
original_list.add(original_list.size(), id.next());
}
}
if (insert_data.size() == 1) {
notifyItemInserted(start);
} else if (insert_data.size() > 1) {
notifyItemRangeInserted(start, insert_data.size());
}
if (enabled_custom_load_more_view) {
revealDispatchLoadMoreView();
}
} catch (Exception e) {
String o = e.fillInStackTrace().getCause().getMessage().toString();
Log.d("fillInStackTrace", o + " : ");
}
}
/**
* Remove a item of the list of the adapter
*
* @param list na
* @param position na
* @param na
*/
public final void removeInternal(List list, int position) {
if (hasHeaderView() && position == 0) return;
if (enableLoadMore() && position == getItemCount() - 1) return;
if (list.size() > 0) {
synchronized (mLock) {
list.remove(hasHeaderView() ? position - 1 : position);
}
removeNotifyExternal(position);
notifyItemRemoved(position);
}
}
protected void removeNotifyExternal(final int pos) {
}
public final void removeFirstInternal(List list) {
removeInternal(list, 0);
}
public final void removeLastInternal(List list) {
removeInternal(list, getAdapterItemCount() - 1);
}
/**
* Clear the list of the adapter
*
* @param list data list
* @param na
*/
public final void clearInternal(List list) {
int data_size_before_remove = list.size();
final int display_size_before_remove = getItemCount();
synchronized (mLock) {
list.clear();
}
notifyAfterRemoveAllData(data_size_before_remove, display_size_before_remove);
}
/**
* @param data_size_before_remove data size
* @param display_size_before_remove display item size
* @return TRUE for this is done and no more further processing
*/
protected boolean detectDispatchLoadMoreDisplay(final int data_size_before_remove, final int display_size_before_remove) {
if (data_size_before_remove == 0) {
if (display_size_before_remove == 2) {
if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE) {
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER) {
removeDispatchLoadMoreView();
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_CLEAR_ALL) {
removeDispatchLoadMoreView();
}
} else if (display_size_before_remove == 1) {
if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE) {
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER) {
removeDispatchLoadMoreView();
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_CLEAR_ALL) {
removeDispatchLoadMoreView();
}
return true;
} else if (display_size_before_remove == 0) {
if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE) {
notifyDataSetChanged();
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER) {
notifyDataSetChanged();
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_SHOW_LOADMORE_ONLY) {
notifyDataSetChanged();
}
return true;
} else {
return false;
}
}
return false;
}
protected void revealDispatchLoadMoreView() {
if (customLoadMoreItemView != null) {
if (customLoadMoreItemView.getVisibility() != View.VISIBLE) {
customLoadMoreItemView.setVisibility(View.VISIBLE);
}
}
}
protected void removeDispatchLoadMoreView() {
if (customLoadMoreItemView != null) {
if (customLoadMoreItemView.getVisibility() != View.GONE) {
customLoadMoreItemView.setVisibility(View.GONE);
}
}
}
/**
* works on API v23
* there is a high chance to crash this
*
* @param data_size_before_remove original size before removed
* @param display_size_before_remove the counts for display items
*
* http://stackoverflow.com/questions/30220771/recyclerview-inconsistency-detected-invalid-item-position
*/
protected void notifyAfterRemoveAllData(final int data_size_before_remove, final int display_size_before_remove) {
try {
final int notify_start_item = hasHeaderView() ? 1 : 0;
final int notifiy_n_plus = hasHeaderView() ? data_size_before_remove + 1 : data_size_before_remove;
if (detectDispatchLoadMoreDisplay(data_size_before_remove, display_size_before_remove))
return;
if (data_size_before_remove == 0) return;
if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE) {
if (hasHeaderView())
notifyItemRangeChanged(notify_start_item, data_size_before_remove);
else {
notifyDataSetChanged();
}
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_KEEP_HEADER) {
notifyItemRangeRemoved(notify_start_item, data_size_before_remove);
removeDispatchLoadMoreView();
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_CLEAR_ALL) {
notifyItemRangeRemoved(0, notifiy_n_plus);
removeDispatchLoadMoreView();
} else if (mEmptyViewPolicy == UltimateRecyclerView.EMPTY_SHOW_LOADMORE_ONLY) {
notifyItemRangeRemoved(0, notifiy_n_plus);
revealDispatchLoadMoreView();
} else {
notifyItemRangeRemoved(0, notifiy_n_plus);
}
} catch (Exception e) {
String o = e.fillInStackTrace().getCause().getMessage().toString();
Log.d("fillInStackTrace", o + " : ");
}
}
/**
* remove all items
*
* @param list na
* @param na
*/
public final void removeAllInternal(List list) {
clearInternal(list);
}
@Override
public long getHeaderId(int position) {
if (hasHeaderView() && position == 0) return -1;
if (enableLoadMore() && position >= getItemCount() - 1) return -1;
if (getAdapterItemCount() > 0) {
return generateHeaderId(hasHeaderView() ? position - 1 : position);
} else return -1;
}
public abstract long generateHeaderId(int position);
public static class VIEW_TYPES {
public static final int NORMAL = 0;
public static final int HEADER = 1;
//this is the default loading footer
public static final int FOOTER = 2;
//this is the customized footer
public static final int NOVIEW = 3;
//this is specialized Ad view
public static final int ADVIEW = 4;
public static final int CUSTOMVIEW = 5;
public static final int SECTION = 6;
}
protected enum AdapterAnimationType {
AlphaIn,
SlideInBottom,
ScaleIn,
SlideInLeft,
SlideInRight,
}
/**
* Animations when loading the adapter
*
* @param view the view
* @param type the type of the animation
* @return the animator in array
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected Animator[] getAdapterAnimations(View view, AdapterAnimationType type) {
if (type == AdapterAnimationType.ScaleIn) {
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", .5f, 1f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", .5f, 1f);
return new ObjectAnimator[]{scaleX, scaleY};
} else if (type == AdapterAnimationType.AlphaIn) {
return new Animator[]{ObjectAnimator.ofFloat(view, "alpha", .5f, 1f)};
} else if (type == AdapterAnimationType.SlideInBottom) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0)
};
} else if (type == AdapterAnimationType.SlideInLeft) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationX", -view.getRootView().getWidth(), 0)
};
} else if (type == AdapterAnimationType.SlideInRight) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationX", view.getRootView().getWidth(), 0)
};
}
return null;
}
/*
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ViewHelper.clear(holder.itemView);
}
*/
@Override
public void onItemMove(int fromPosition, int toPosition) {
notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
if (hasHeaderView() && getItemViewType(position) == VIEW_TYPES.HEADER) return;
if (enableLoadMore() && getItemViewType(position) == VIEW_TYPES.FOOTER) return;
notifyDataSetChanged();
}
protected OnStartDragListener mDragStartListener = null;
/**
* Listener for manual initiation of a drag.
*/
public interface OnStartDragListener {
/**
* Called when a view is requesting a start of a drag.
*
* @param viewHolder The holder of the view to drag.
*/
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/PageControlConst.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator;
/**
* Created by zJJ on 2/21/2016.
*/
public class PageControlConst {
public static String FRAGMENTTITLE = "fragment_title";
public static String SAVELOADDATA = "item_list";
public static String HASSAVEFILTER = "filter";
public static String URL = "data_url";
public final static String
BRAND_NAME = "BrandName",
SLUGTAG = "slug",
REQUEST_TYPE = "typerequest";
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/catelogGrid.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.R;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
/**
* Created by hesk on 15/2/16.
*/
public abstract class catelogGrid extends paginator {
public static String TAG = "catelog";
public UltimateRecyclerView listview_layout;
protected GridLayoutManager mLayoutManager;
protected adapter madapter;
protected abstract adapter getAdatperWithdata();
protected abstract void setUltimateRecyclerViewExtra(final UltimateRecyclerView listview, final adapter madapter);
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentResId(), container, false);
}
@Override
@IdRes
protected int getUltimate_recycler_viewResId() {
return R.id.urv_main_list;
}
@Override
@IdRes
protected int getRefresherProgressBarId() {
return R.id.urv_main_progress_bar;
}
protected abstract int getColumn();
/**
* step 1:
* takes the arguement form the intent bundle and determine if there is a need to queue a loading process. If that is a yes then we need to load up the data before displaying the list out.
*
* @param r and the data bundle
* @return tells if there is a loading process to be done before hand
*/
protected abstract boolean onArguments(final Bundle r);
/**
* step 2:
* this is the call for the loading the data stream externally
*
* @param confirmAdapter the adapter
*/
protected abstract void loadDataInitial(final adapter confirmAdapter);
protected void renderviewlayout(View view) throws Exception {
listview_layout = (UltimateRecyclerView) view.findViewById(getUltimate_recycler_viewResId());
listview_layout.setHasFixedSize(true);
listview_layout.setSaveEnabled(true);
if (mLayoutManager == null) {
mLayoutManager = new GridLayoutManager(view.getContext(), getColumn(), LinearLayoutManager.VERTICAL, false);
}
listview_layout.setLayoutManager(mLayoutManager);
getProgressbar(view);
listview_layout.setAdapter(madapter = getAdatperWithdata());
setUltimateRecyclerViewExtra(listview_layout, madapter);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
try {
renderviewlayout(view);
if (getArguments() != null) {
if (onArguments(getArguments())) {
showLoadingCircle();
initPaginator();
loadDataInitial(madapter);
}
}
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/catelogLinear.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.R;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import com.marshalchen.ultimaterecyclerview.layoutmanagers.ScrollSmoothLineaerLayoutManager;
/**
* Created by hesk on 30/6/15.
*/
public abstract class catelogLinear extends paginator {
public static String TAG = "catelog";
public final static String BRAND_NAME = "BrandName", SLUG = "slug", REQUEST_TYPE = "typerequest";
public UltimateRecyclerView listview_layout;
public static String URL = "data_url";
public static String FRAGMENTTITLE = "fragment_title";
public static String SAVELOADDATA = "item_list";
public static String HASSAVEFILTER = "filter";
protected LinearLayoutManager mLayoutManager;
protected adapter madapter;
protected abstract adapter getAdatperWithdata();
protected abstract void setUltimateRecyclerViewExtra(final UltimateRecyclerView listview, final adapter madapter);
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentResId(), container, false);
}
@IdRes
protected int getUltimate_recycler_viewResId() {
return R.id.urv_main_list;
}
@IdRes
protected int getRefresherProgressBarId() {
return R.id.urv_main_progress_bar;
}
/**
* step 1:
* takes the arguement form the intent bundle and determine if there is a need to queue a loading process. If that is a yes then we need to load up the data before displaying the list out.
*
* @param r and the data bundle
* @return tells if there is a loading process to be done before hand
*/
protected abstract boolean onArguments(final Bundle r);
/**
* step 2:
* this is the call for the loading the data stream externally
*
* @param confirmAdapter the adapter
*/
protected abstract void loadDataInitial(final adapter confirmAdapter);
protected void renderviewlayout(View view) throws Exception {
listview_layout = (UltimateRecyclerView) view.findViewById(getUltimate_recycler_viewResId());
listview_layout.setHasFixedSize(true);
listview_layout.setSaveEnabled(true);
if (mLayoutManager == null) {
mLayoutManager = new ScrollSmoothLineaerLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false, getSmoothDuration());
}
listview_layout.setLayoutManager(mLayoutManager);
listview_layout.setAdapter(madapter = getAdatperWithdata());
getProgressbar(view);
setUltimateRecyclerViewExtra(listview_layout, madapter);
}
protected int getSmoothDuration() {
return 300;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
try {
renderviewlayout(view);
if (getArguments() != null) {
if (onArguments(getArguments())) {
showLoadingCircle();
initPaginator();
loadDataInitial(madapter);
}
}
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/paginator.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator;
import android.app.Fragment;
import android.os.Build;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import android.view.View;
import android.widget.ProgressBar;
/**
* Created by hesk on 15/2/16.
*/
public abstract class paginator extends Fragment {
private int currentPage, totalPages, pagePerItems, landscape_common_colums = 4, portrait_common_colums = 2;
private String tag_keyword, fullEndPoint, searchKeyword;
private boolean enable_load_more, is_new_search, status_refresh, status_initization;
protected ProgressBar mProgress;
protected void getProgressbar(View view, @IdRes final int progress_bar_id) {
try {
mProgress = (ProgressBar) view.findViewById(progress_bar_id);
} catch (Exception e) {
//unable to find loading progress bar
}
}
protected void getProgressbar(View view) {
try {
mProgress = (ProgressBar) view.findViewById(getRefresherProgressBarId());
} catch (Exception e) {
//unable to find loading progress bar
}
}
public final void cancelInitalization() {
status_initization = false;
}
public final boolean isInitization() {
return status_initization;
}
public final void setIsStatusRefresh(boolean b) {
status_refresh = b;
}
public final boolean isStatusRefresh() {
return status_refresh;
}
@IdRes
protected abstract int getRefresherProgressBarId();
@IdRes
protected abstract int getUltimate_recycler_viewResId();
@LayoutRes
protected abstract int getFragmentResId();
protected abstract void onClickItem(final String route);
protected abstract void onClickItem(final long route_id);
protected void showLoadingCircle() {
if (mProgress != null) {
mProgress.setVisibility(View.VISIBLE);
mProgress.animate().alpha(1f);
}
}
protected void hideLoadingCircle() {
if (mProgress != null && mProgress.getVisibility() == View.VISIBLE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProgress.animate().alpha(0f).withEndAction(new Runnable() {
@Override
public void run() {
mProgress.setVisibility(View.INVISIBLE);
}
});
} else {
mProgress.setVisibility(View.INVISIBLE);
}
}
}
protected int getItemsShownPerPage() {
return 16;
}
protected void initPaginator() {
currentPage = 1;
totalPages = 1;
pagePerItems = getItemsShownPerPage();
enable_load_more = false;
is_new_search = false;
status_initization = true;
}
public String getSearchKeyword() {
return searchKeyword;
}
public void setSearchKeyword(String searchKeyword) {
this.searchKeyword = searchKeyword;
}
public String getTagKeyword() {
return tag_keyword;
}
public void setTagKeyword(String tag_keyword) {
this.tag_keyword = tag_keyword;
}
public String getFullEndPoint() {
return fullEndPoint;
}
public void setFullEndPoint(String fullEndPoint) {
this.fullEndPoint = fullEndPoint;
}
public boolean isNewSearch() {
return is_new_search;
}
public void setEnablNewSearch(boolean is_new_search) {
this.is_new_search = is_new_search;
}
protected int getCurrentPage() {
return currentPage;
}
protected int getTotalPages() {
return totalPages;
}
protected int getPagePerItems() {
return pagePerItems;
}
protected void setCurrentPage(int n) {
currentPage = n;
}
protected void nextPage() {
if (currentPage < totalPages) {
enable_load_more = true;
currentPage++;
}
}
protected void setTotalPages(int n) {
totalPages = n;
if (currentPage >= totalPages) {
enable_load_more = false;
} else {
enable_load_more = true;
}
}
protected boolean shouldEnableLoadMore() {
return enable_load_more;
}
public void triggerNewSearchKeyWord(String word) {
setEnablNewSearch(true);
setSearchKeyword(word);
}
protected abstract void makeBasicRequest();
protected abstract void makeRefreshRequest();
protected void makeNextRequest() {
nextPage();
makeBasicRequest();
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/v4/catelogGrid.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator.v4;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.R;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
/**
* Created by hesk on 15/2/16.
*/
public abstract class catelogGrid extends paginator {
public static String TAG = "catelog";
public UltimateRecyclerView listview_layout;
protected GridLayoutManager mLayoutManager;
protected adapter madapter;
protected abstract adapter getAdatperWithdata();
protected abstract void setUltimateRecyclerViewExtra(final UltimateRecyclerView listview, final adapter madapter);
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentResId(), container, false);
}
@Override
@IdRes
protected int getUltimate_recycler_viewResId() {
return R.id.urv_main_list;
}
@Override
@IdRes
protected int getRefresherProgressBarId() {
return R.id.urv_main_progress_bar;
}
protected abstract int getColumn();
/**
* step 1:
* takes the arguement form the intent bundle and determine if there is a need to queue a loading process. If that is a yes then we need to load up the data before displaying the list out.
*
* @param r and the data bundle
* @return tells if there is a loading process to be done before hand
*/
protected abstract boolean onArguments(final Bundle r);
/**
* step 2:
* this is the call for the loading the data stream externally
*
* @param confirmAdapter the adapter
*/
protected abstract void loadDataInitial(final adapter confirmAdapter);
protected void renderviewlayout(View view) throws Exception {
listview_layout = (UltimateRecyclerView) view.findViewById(getUltimate_recycler_viewResId());
listview_layout.setHasFixedSize(true);
listview_layout.setSaveEnabled(true);
if (mLayoutManager == null) {
mLayoutManager = new GridLayoutManager(view.getContext(), getColumn(), LinearLayoutManager.VERTICAL, false);
}
listview_layout.setLayoutManager(mLayoutManager);
getProgressbar(view);
listview_layout.setAdapter(madapter = getAdatperWithdata());
setUltimateRecyclerViewExtra(listview_layout, madapter);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
try {
renderviewlayout(view);
if (getArguments() != null) {
if (onArguments(getArguments())) {
showLoadingCircle();
initPaginator();
loadDataInitial(madapter);
}
}
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/v4/catelogLinear.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator.v4;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.R;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter;
import com.marshalchen.ultimaterecyclerview.layoutmanagers.ScrollSmoothLineaerLayoutManager;
/**
* Created by hesk on 30/6/15.
*/
public abstract class catelogLinear extends paginator {
public static String TAG = "catelog";
public final static String BRAND_NAME = "BrandName", SLUG = "slug", REQUEST_TYPE = "typerequest";
public UltimateRecyclerView listview_layout;
public static String URL = "data_url";
public static String FRAGMENTTITLE = "fragment_title";
public static String SAVELOADDATA = "item_list";
public static String HASSAVEFILTER = "filter";
protected LinearLayoutManager mLayoutManager;
protected adapter madapter;
protected abstract adapter getAdatperWithdata();
protected abstract void setUltimateRecyclerViewExtra(final UltimateRecyclerView listview, final adapter madapter);
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentResId(), container, false);
}
@IdRes
protected int getUltimate_recycler_viewResId() {
return R.id.urv_main_list;
}
@IdRes
protected int getRefresherProgressBarId() {
return R.id.urv_main_progress_bar;
}
/**
* step 1:
* takes the arguement form the intent bundle and determine if there is a need to queue a loading process. If that is a yes then we need to load up the data before displaying the list out.
*
* @param r and the data bundle
* @return tells if there is a loading process to be done before hand
*/
protected abstract boolean onArguments(final Bundle r);
/**
* step 2:
* this is the call for the loading the data stream externally
*
* @param confirmAdapter the adapter
*/
protected abstract void loadDataInitial(final adapter confirmAdapter);
protected void renderviewlayout(View view) throws Exception {
listview_layout = (UltimateRecyclerView) view.findViewById(getUltimate_recycler_viewResId());
listview_layout.setHasFixedSize(true);
listview_layout.setSaveEnabled(true);
if (mLayoutManager == null) {
mLayoutManager = new ScrollSmoothLineaerLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false, getSmoothDuration());
}
listview_layout.setLayoutManager(mLayoutManager);
listview_layout.setAdapter(madapter = getAdatperWithdata());
getProgressbar(view);
setUltimateRecyclerViewExtra(listview_layout, madapter);
}
protected int getSmoothDuration() {
return 300;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
try {
renderviewlayout(view);
if (getArguments() != null) {
if (onArguments(getArguments())) {
showLoadingCircle();
initPaginator();
loadDataInitial(madapter);
}
}
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/appPaginator/v4/paginator.java
================================================
package com.marshalchen.ultimaterecyclerview.appPaginator.v4;
import android.os.Build;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.fragment.app.Fragment;
import android.view.View;
import android.widget.ProgressBar;
/**
* Created by hesk on 15/2/16.
*/
public abstract class paginator extends Fragment {
private int currentPage, totalPages, pagePerItems, landscape_common_colums = 4, portrait_common_colums = 2;
private String tag_keyword, fullEndPoint, searchKeyword;
private boolean enable_load_more, is_new_search, status_refresh, status_initization;
protected ProgressBar mProgress;
protected void getProgressbar(View view, @IdRes final int progress_bar_id) {
try {
mProgress = (ProgressBar) view.findViewById(progress_bar_id);
} catch (Exception e) {
//unable to find loading progress bar
}
}
protected void getProgressbar(View view) {
try {
mProgress = (ProgressBar) view.findViewById(getRefresherProgressBarId());
} catch (Exception e) {
//unable to find loading progress bar
}
}
public final void cancelInitalization() {
status_initization = false;
}
public final boolean isInitization() {
return status_initization;
}
public final void setIsStatusRefresh(boolean b) {
status_refresh = b;
}
public final boolean isStatusRefresh() {
return status_refresh;
}
@IdRes
protected abstract int getRefresherProgressBarId();
@IdRes
protected abstract int getUltimate_recycler_viewResId();
@LayoutRes
protected abstract int getFragmentResId();
protected abstract void onClickItem(final String route);
protected abstract void onClickItem(final long route_id);
protected void showLoadingCircle() {
if (mProgress != null) {
mProgress.setVisibility(View.VISIBLE);
mProgress.animate().alpha(1f);
}
}
protected void hideLoadingCircle() {
if (mProgress != null && mProgress.getVisibility() == View.VISIBLE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProgress.animate().alpha(0f).withEndAction(new Runnable() {
@Override
public void run() {
mProgress.setVisibility(View.INVISIBLE);
}
});
} else {
mProgress.setVisibility(View.INVISIBLE);
}
}
}
protected int getItemsShownPerPage() {
return 16;
}
protected void initPaginator() {
currentPage = 1;
totalPages = 1;
pagePerItems = getItemsShownPerPage();
enable_load_more = false;
is_new_search = false;
status_initization = true;
}
public String getSearchKeyword() {
return searchKeyword;
}
public void setSearchKeyword(String searchKeyword) {
this.searchKeyword = searchKeyword;
}
public String getTagKeyword() {
return tag_keyword;
}
public void setTagKeyword(String tag_keyword) {
this.tag_keyword = tag_keyword;
}
public String getFullEndPoint() {
return fullEndPoint;
}
public void setFullEndPoint(String fullEndPoint) {
this.fullEndPoint = fullEndPoint;
}
public boolean isNewSearch() {
return is_new_search;
}
public void setEnablNewSearch(boolean is_new_search) {
this.is_new_search = is_new_search;
}
protected int getCurrentPage() {
return currentPage;
}
protected int getTotalPages() {
return totalPages;
}
protected int getPagePerItems() {
return pagePerItems;
}
protected void setCurrentPage(int n) {
currentPage = n;
}
protected void nextPage() {
if (currentPage < totalPages) {
enable_load_more = true;
currentPage++;
}
}
protected void setTotalPages(int n) {
totalPages = n;
if (currentPage >= totalPages) {
enable_load_more = false;
} else {
enable_load_more = true;
}
}
protected boolean shouldEnableLoadMore() {
return enable_load_more;
}
public void triggerNewSearchKeyWord(String word) {
setEnablNewSearch(true);
setSearchKeyword(word);
}
protected abstract void makeBasicRequest();
protected abstract void makeRefreshRequest();
protected void makeNextRequest() {
nextPage();
makeBasicRequest();
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/dragsortadapter/DragInfo.java
================================================
package com.marshalchen.ultimaterecyclerview.dragsortadapter;
import android.graphics.Point;
import android.graphics.PointF;
public class DragInfo {
private final long itemId;
private final Point shadowSize;
private final Point shadowTouchPoint;
private final PointF dragPoint;
public DragInfo(long itemId, Point shadowSize, Point shadowTouchPoint, PointF dragPoint) {
this.itemId = itemId;
this.shadowSize = new Point(shadowSize);
this.shadowTouchPoint = new Point(shadowTouchPoint);
this.dragPoint = dragPoint;
}
public long itemId() {
return itemId;
}
public boolean shouldScrollLeft() {
return dragPoint.x < shadowTouchPoint.x;
}
public boolean shouldScrollRight(int parentWidth) {
return dragPoint.x > (parentWidth - (shadowSize.x - shadowTouchPoint.x));
}
public boolean shouldScrollUp() {
return dragPoint.y < shadowTouchPoint.y;
}
public boolean shouldScrollDown(int parentHeight) {
return dragPoint.y > (parentHeight - (shadowSize.y - shadowTouchPoint.y));
}
public void setDragPoint(float x, float y) {
dragPoint.set(x, y);
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/dragsortadapter/DragManager.java
================================================
package com.marshalchen.ultimaterecyclerview.dragsortadapter;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.DragEvent;
import android.view.View;
import java.lang.ref.WeakReference;
import static java.lang.Float.MIN_VALUE;
public class DragManager implements View.OnDragListener {
private final WeakReference recyclerViewRef;
private final DragSortAdapter> adapter;
private long draggingId = RecyclerView.NO_ID;
private final PointF nextMoveTouchPoint = new PointF(MIN_VALUE, MIN_VALUE);
@Nullable private DragInfo lastDragInfo;
public DragManager(RecyclerView recyclerView, DragSortAdapter> adapter) {
this.recyclerViewRef = new WeakReference<>(recyclerView);
this.adapter = adapter;
}
@Override public boolean onDrag(View v, DragEvent event) {
if (v != recyclerViewRef.get() || !(event.getLocalState() instanceof DragInfo)) {
return false;
}
final RecyclerView recyclerView = (RecyclerView) v;
final DragInfo dragInfo = (DragInfo) event.getLocalState();
final long itemId = dragInfo.itemId();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
draggingId = itemId;
adapter.notifyItemChanged(recyclerView.findViewHolderForItemId(itemId).getAdapterPosition());
break;
case DragEvent.ACTION_DRAG_LOCATION:
float x = event.getX();
float y = event.getY();
int fromPosition = adapter.getPositionForId(itemId);
int toPosition = -1;
View child = recyclerView.findChildViewUnder(event.getX(), event.getY());
if (child != null) {
toPosition = recyclerView.getChildViewHolder(child).getAdapterPosition();
}
if (toPosition >= 0 && fromPosition != toPosition) {
RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
boolean scheduleNextMove = nextMoveTouchPoint.equals(MIN_VALUE, MIN_VALUE);
nextMoveTouchPoint.set(x, y);
if (scheduleNextMove)
animator.isRunning(new RecyclerView.ItemAnimator.ItemAnimatorFinishedListener() {
@Override public void onAnimationsFinished() {
if (nextMoveTouchPoint.equals(MIN_VALUE, MIN_VALUE)) { return; }
final int fromPosition = adapter.getPositionForId(itemId);
View child = recyclerView
.findChildViewUnder(nextMoveTouchPoint.x, nextMoveTouchPoint.y);
if (child != null) {
final int toPosition =
recyclerView.getChildViewHolder(child).getAdapterPosition();
if (adapter.move(fromPosition, toPosition)) {
if (fromPosition == 0 || toPosition == 0) {
// fix for weird scrolling when animating first item
recyclerView.scrollToPosition(0);
}
recyclerView.post(new Runnable() {
@Override public void run() {
adapter.notifyItemMoved(fromPosition, toPosition);
}
});
}
}
// reset so we know to schedule listener again next time
clearNextMove();
}
});
}
lastDragInfo = dragInfo;
lastDragInfo.setDragPoint(x, y);
adapter.handleDragScroll(recyclerView, dragInfo);
break;
case DragEvent.ACTION_DRAG_ENDED:
draggingId = RecyclerView.NO_ID;
lastDragInfo = null;
// queue up the show animation until after all move animations are finished
recyclerView.getItemAnimator().isRunning(
new RecyclerView.ItemAnimator.ItemAnimatorFinishedListener() {
@Override public void onAnimationsFinished() {
int position = adapter.getPositionForId(itemId);
RecyclerView.ViewHolder vh = recyclerView.findViewHolderForItemId(itemId);
if (vh != null && vh.getAdapterPosition() != position) {
// if positions don't match, there's still an outstanding move animation
// so we try to reschedule the notifyItemChanged until after that
recyclerView.post(new Runnable() {
@Override public void run() {
recyclerView.getItemAnimator().isRunning(
new RecyclerView.ItemAnimator.ItemAnimatorFinishedListener() {
@Override public void onAnimationsFinished() {
adapter.notifyItemChanged(adapter.getPositionForId(itemId));
}
});
}
});
} else {
adapter.notifyItemChanged(adapter.getPositionForId(itemId));
}
}
});
break;
case DragEvent.ACTION_DROP:
adapter.onDrop();
break;
case DragEvent.ACTION_DRAG_ENTERED:
// probably not used?
break;
case DragEvent.ACTION_DRAG_EXITED:
// TODO edge scrolling
break;
}
return true;
}
public void clearNextMove() {
nextMoveTouchPoint.set(MIN_VALUE, MIN_VALUE);
}
public long getDraggingId() { return draggingId; }
@Nullable public DragInfo getLastDragInfo() { return lastDragInfo; }
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/dragsortadapter/DragSortAdapter.java
================================================
/*
* Copyright (C) 2015 Vincent Mi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.dragsortadapter;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.Build;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
public abstract class DragSortAdapter
extends RecyclerView.Adapter {
private static final String TAG = DragSortAdapter.class.getSimpleName();
private final int SCROLL_AMOUNT = (int) (2 * Resources.getSystem().getDisplayMetrics().density);
private final DragManager dragManager;
private int scrollState = RecyclerView.SCROLL_STATE_IDLE;
private final PointF lastTouchPoint = new PointF(); // used to create ShadowBuilder
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public DragSortAdapter(RecyclerView recyclerView) {
setHasStableIds(true);
dragManager = new DragManager(recyclerView, this);
recyclerView.setOnDragListener(dragManager);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
lastTouchPoint.set(e.getX(), e.getY());
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(final RecyclerView recyclerView, int dx, int dy) {
recyclerView.post(new Runnable() {
@Override
public void run() {
handleScroll(recyclerView);
}
});
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
scrollState = newState;
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE:
handleScroll(recyclerView);
break;
case RecyclerView.SCROLL_STATE_DRAGGING:
case RecyclerView.SCROLL_STATE_SETTLING:
break;
}
}
});
}
/**
* This should be reasonably performant as it gets called a lot on the UI thread.
*
* @param id na
* @return position of the item with the given id
*/
public abstract int getPositionForId(long id);
/**
* This is called during the dragging event, the actual positions of the views and data need to
* change in the adapter for the drag animations to look correct.
*
* @param fromPosition from position
* @param toPosition to position
* @return true if the position can be moved from fromPosition to toPosition
*/
public abstract boolean move(int fromPosition, int toPosition);
/**
* Called after a drop event, override to save changes after drop event.
*/
public void onDrop() {
}
/**
* You probably want to use this to set the currently dragging item to blank while it's being
* dragged
*
* @return the id of the item currently being dragged or {@code RecyclerView.NO_ID } if not being
* dragged
*/
public long getDraggingId() {
return dragManager.getDraggingId();
}
/**
* @return PointF
*/
public PointF getLastTouchPoint() {
return new PointF(lastTouchPoint.x, lastTouchPoint.y);
}
private void handleScroll(RecyclerView recyclerView) {
if (scrollState != RecyclerView.SCROLL_STATE_IDLE) {
return;
}
DragInfo lastDragInfo = dragManager.getLastDragInfo();
if (lastDragInfo != null) {
handleDragScroll(recyclerView, lastDragInfo);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void handleDragScroll(RecyclerView rv, DragInfo dragInfo) {
if (rv.getLayoutManager().canScrollHorizontally()) {
if (rv.canScrollHorizontally(-1) && dragInfo.shouldScrollLeft()) {
rv.scrollBy(-SCROLL_AMOUNT, 0);
dragManager.clearNextMove();
} else if (rv.canScrollHorizontally(1) && dragInfo.shouldScrollRight(rv.getWidth())) {
rv.scrollBy(SCROLL_AMOUNT, 0);
dragManager.clearNextMove();
}
} else if (rv.getLayoutManager().canScrollVertically()) {
if (rv.canScrollVertically(-1) && dragInfo.shouldScrollUp()) {
rv.scrollBy(0, -SCROLL_AMOUNT);
dragManager.clearNextMove();
} else if (rv.canScrollVertically(1) && dragInfo.shouldScrollDown(rv.getHeight())) {
rv.scrollBy(0, SCROLL_AMOUNT);
dragManager.clearNextMove();
}
}
}
public static abstract class ViewHolder extends RecyclerView.ViewHolder {
final DragSortAdapter> adapter;
public ViewHolder(DragSortAdapter> dragSortAdapter, View itemView) {
super(itemView);
this.adapter = dragSortAdapter;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public final void startDrag() {
PointF touchPoint = adapter.getLastTouchPoint();
int x = (int) (touchPoint.x - itemView.getX());
int y = (int) (touchPoint.y - itemView.getY());
startDrag(getShadowBuilder(itemView, new Point(x, y)));
}
public View.DragShadowBuilder getShadowBuilder(View itemView, Point touchPoint) {
return new DragSortShadowBuilder(itemView, touchPoint);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public final void startDrag(View.DragShadowBuilder dragShadowBuilder) {
Point shadowSize = new Point();
Point shadowTouchPoint = new Point();
dragShadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
itemView.startDrag(null, dragShadowBuilder,
new DragInfo(getItemId(), shadowSize, shadowTouchPoint, adapter.getLastTouchPoint()), 0);
adapter.notifyItemChanged(getAdapterPosition());
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/dragsortadapter/DragSortShadowBuilder.java
================================================
/*
* Copyright (C) 2015 Vincent Mi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marshalchen.ultimaterecyclerview.dragsortadapter;
import android.annotation.TargetApi;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Build;
import androidx.annotation.NonNull;
import android.util.Log;
import android.view.View;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DragSortShadowBuilder extends View.DragShadowBuilder {
public static final String TAG = DragSortShadowBuilder.class.getSimpleName();
final Point touchPoint = new Point();
public DragSortShadowBuilder(View view, Point touchPoint) {
super(view);
this.touchPoint.set(touchPoint.x, touchPoint.y);
}
@Override
public void onProvideShadowMetrics(@NonNull Point shadowSize, @NonNull Point shadowTouchPoint) {
final View view = getView();
if (view != null) {
shadowSize.set(view.getWidth(), view.getHeight());
shadowTouchPoint.set(touchPoint.x, touchPoint.y);
} else {
Log.e(TAG, "Asked for drag thumb metrics but no view");
}
}
@Override public void onDrawShadow(@NonNull Canvas canvas) {
super.onDrawShadow(canvas);
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/dragsortadapter/NoForegroundShadowBuilder.java
================================================
package com.marshalchen.ultimaterecyclerview.dragsortadapter;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import java.lang.ref.WeakReference;
public class NoForegroundShadowBuilder extends DragSortShadowBuilder {
private final WeakReference viewRef;
public NoForegroundShadowBuilder(View view, Point touchPoint) {
super(view, touchPoint);
this.viewRef = new WeakReference<>(view);
}
@Override public void onDrawShadow(@NonNull Canvas canvas) {
final View view = viewRef.get();
if (view != null) {
Drawable foreground = null;
// remove foreground before canvas draw
if (view instanceof FrameLayout && ((FrameLayout) view).getForeground() != null) {
foreground = ((FrameLayout) view).getForeground();
((FrameLayout) view).setForeground(null);
}
view.draw(canvas);
// reset foreground if it was removed
if (foreground != null) {
((FrameLayout) view).setForeground(foreground);
}
} else {
Log.e(TAG, "Asked to draw drag shadow but no view");
}
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/expanx/ExpandableItemData.java
================================================
package com.marshalchen.ultimaterecyclerview.expanx;
import java.util.List;
/**
* Author Zheng Haibo
* PersonalWebsite http://www.mobctrl.net
* Description the bundle of the tree view style
* enhanced by Hesk 2015
* used with LinearExpandableURVAdapter
*/
public class ExpandableItemData implements Comparable {
private String uuid;
private int type;
private String text;
private String path;
private int treeDepth = 0;
private List children;
private boolean expand;
public boolean isExpand() {
return expand;
}
public void setExpand(boolean expand) {
this.expand = expand;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
}
public ExpandableItemData(int type, String text, String path, String uuid,
int treeDepth, List children) {
super();
this.type = type;
this.text = text;
this.uuid = uuid;
this.path = path;
this.treeDepth = treeDepth;
this.children = children;
}
public ExpandableItemData() {
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getTreeDepth() {
return treeDepth;
}
public void setTreeDepth(int treeDepth) {
this.treeDepth = treeDepth;
}
@Override
public int compareTo(ExpandableItemData another) {
return this.getText().compareTo(another.getText());
}
}
================================================
FILE: UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/expanx/LinearExpanxURVAdapter.java
================================================
package com.marshalchen.ultimaterecyclerview.expanx;
import android.content.Context;
import androidx.annotation.LayoutRes;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.marshalchen.ultimaterecyclerview.expanx.Util.BaseViewHolder;
import com.marshalchen.ultimaterecyclerview.expanx.Util.ChildVH;
import com.marshalchen.ultimaterecyclerview.expanx.Util.ItemDataClickListener;
import com.marshalchen.ultimaterecyclerview.expanx.Util.OnScrollToListener;
import com.marshalchen.ultimaterecyclerview.expanx.Util.ParentVH;
import com.marshalchen.ultimaterecyclerview.expanx.Util.child;
import com.marshalchen.ultimaterecyclerview.expanx.Util.parent;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hesk on 16/7/15.
*/
public abstract class LinearExpanxURVAdapter, H extends child> extends UltimateViewAdapter {
public class ExpandableViewTypes extends VIEW_TYPES {
public static final int ITEM_TYPE_PARENT = 1026;
public static final int ITEM_TYPE_CHILD = 1135;
protected ExpandableViewTypes() {
super();
}
}
private Context mContext;
private List mDataSet;
private List monScrollToListenerList = new ArrayList<>();
private OnScrollToListener onScrollToListener;
public static final String TAG = "expAdapter";
protected int expandableBehavior = 0;
public static final int EXPANDABLE_ITEMS = 1;
public static final int EXPANDABLE_SYSTEM = 0;
private boolean customObject;
protected Context getContext() {
return mContext;
}
protected List getSet() {
return mDataSet;
}
public void addOnScrollToListener(OnScrollToListener onScrollToListener) {
this.monScrollToListenerList.add(onScrollToListener);
}
@Deprecated
public void setOnScrollToListener(OnScrollToListener onScrollToListener) {
this.onScrollToListener = onScrollToListener;
}
public LinearExpanxURVAdapter(Context context, final int clickhandler, final boolean customholder) {
this(context, clickhandler);
this.customObject = customholder;
}
public LinearExpanxURVAdapter(Context context, final int clickhandler) {
this(context);
expandableBehavior = clickhandler;
}
public LinearExpanxURVAdapter(Context context) {
mContext = context;
mDataSet = new ArrayList<>();
customObject = false;
}
/**
* please do work on this id the custom object is true
*
* @param parentview the inflated view
* @return the actual parent holder
*/
protected abstract G iniCustomParentHolder(View parentview);
/**
* please do work on this if the custom object is true
*
* @param childview the inflated view
* @return the actual child holder
*/
protected abstract H iniCustomChildHolder(View childview);
private View initiateview(ViewGroup parent, final @LayoutRes int layout) {
return LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
}
protected abstract int getLayoutResParent();
protected abstract int getLayoutResChild();
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case ExpandableViewTypes.ITEM_TYPE_PARENT:
return iniCustomParentHolder(initiateview(parent, getLayoutResParent()));
case ExpandableViewTypes.ITEM_TYPE_CHILD:
return iniCustomChildHolder(initiateview(parent, getLayoutResChild()));
default:
return null;
}
}
private ItemDataClickListener getBehavior() {
switch (expandableBehavior) {
case EXPANDABLE_ITEMS:
return imageSetLoadItems;
default:
return imageClickListener;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case ExpandableViewTypes.ITEM_TYPE_PARENT:
ParentVH imageViewHolder = (ParentVH) holder;
imageViewHolder.bindView(mDataSet.get(position), position, getBehavior());
break;
case ExpandableViewTypes.ITEM_TYPE_CHILD:
ChildVH textViewHolder = (ChildVH) holder;
textViewHolder.bindView(mDataSet.get(position), position);
break;
default:
break;
}
}
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup viewGroup) {
return new BaseViewHolder(viewGroup);
}
private void triggerBoardCastEventScrollTo(final int n) {
for (int i = 0; i < monScrollToListenerList.size(); i++) {
OnScrollToListener m = monScrollToListenerList.get(i);
m.scrollTo(n);
}
}
private void triggerSingleEventScrollTo(final int n) {
if (onScrollToListener != null) {
onScrollToListener.scrollTo(n);
}
}
protected abstract List getChildrenByPath(String path, int depth, final int position);
@Override
public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
return null;
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
}
@Override
public int getItemCount() {
return mDataSet.size();
}
/**
* this is the only number coming from the data size
*
* @return the integer from the list count
*/
@Override
public int getAdapterItemCount() {
return getItemCount();
}
@Override
public long generateHeaderId(int i) {
return 0;
}
private int getChildrenCount(T item) {
List