Repository: Bakumon/UGank
Branch: master
Commit: 79b6191d5c7f
Files: 133
Total size: 387.5 KB
Directory structure:
gitextract_vqa0jwoy/
├── .gitignore
├── LICENSE
├── README.md
├── _config.yml
├── app/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ ├── src/
│ │ ├── androidTest/
│ │ │ └── java/
│ │ │ └── me/
│ │ │ └── bakumon/
│ │ │ └── ugank/
│ │ │ └── ExampleInstrumentedTest.java
│ │ ├── main/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── assets/
│ │ │ │ └── litepal.xml
│ │ │ ├── java/
│ │ │ │ └── me/
│ │ │ │ └── bakumon/
│ │ │ │ └── ugank/
│ │ │ │ ├── App.java
│ │ │ │ ├── ConfigManage.java
│ │ │ │ ├── GlobalConfig.java
│ │ │ │ ├── ThemeManage.java
│ │ │ │ ├── base/
│ │ │ │ │ ├── BaseDialog.java
│ │ │ │ │ ├── BasePresenter.java
│ │ │ │ │ ├── BaseView.java
│ │ │ │ │ ├── SwipeBackBaseActivity.java
│ │ │ │ │ └── adapter/
│ │ │ │ │ ├── CommonAdapter4RecyclerView.java
│ │ │ │ │ ├── CommonHolder4RecyclerView.java
│ │ │ │ │ ├── CommonViewPagerAdapter.java
│ │ │ │ │ └── ListenerWithPosition.java
│ │ │ │ ├── entity/
│ │ │ │ │ ├── CategoryResult.java
│ │ │ │ │ ├── Favorite.java
│ │ │ │ │ ├── History.java
│ │ │ │ │ └── SearchResult.java
│ │ │ │ ├── module/
│ │ │ │ │ ├── bigimg/
│ │ │ │ │ │ ├── BigimgActivity.java
│ │ │ │ │ │ ├── BigimgContract.java
│ │ │ │ │ │ └── BigimgPresenter.java
│ │ │ │ │ ├── category/
│ │ │ │ │ │ ├── CategoryContract.java
│ │ │ │ │ │ ├── CategoryFragment.java
│ │ │ │ │ │ ├── CategoryListAdapter.java
│ │ │ │ │ │ └── CategoryPresenter.java
│ │ │ │ │ ├── favorite/
│ │ │ │ │ │ ├── FavoriteActivity.java
│ │ │ │ │ │ ├── FavoriteContract.java
│ │ │ │ │ │ ├── FavoriteListAdapter.java
│ │ │ │ │ │ └── FavoritePresenter.java
│ │ │ │ │ ├── home/
│ │ │ │ │ │ ├── HomeActivity.java
│ │ │ │ │ │ ├── HomeContract.java
│ │ │ │ │ │ └── HomePresenter.java
│ │ │ │ │ ├── launcher/
│ │ │ │ │ │ ├── LauncherActivity.java
│ │ │ │ │ │ ├── LauncherContract.java
│ │ │ │ │ │ └── LauncherPresenter.java
│ │ │ │ │ ├── search/
│ │ │ │ │ │ ├── HistoryListAdapter.java
│ │ │ │ │ │ ├── SearchActivity.java
│ │ │ │ │ │ ├── SearchContract.java
│ │ │ │ │ │ ├── SearchListAdapter.java
│ │ │ │ │ │ └── SearchPresenter.java
│ │ │ │ │ ├── setting/
│ │ │ │ │ │ ├── SettingActivity.java
│ │ │ │ │ │ ├── SettingContract.java
│ │ │ │ │ │ └── SettingPresenter.java
│ │ │ │ │ └── webview/
│ │ │ │ │ ├── WebViewActivity.java
│ │ │ │ │ ├── WebViewContract.java
│ │ │ │ │ └── WebViewPresenter.java
│ │ │ │ ├── network/
│ │ │ │ │ ├── NetWork.java
│ │ │ │ │ └── api/
│ │ │ │ │ └── GankApi.java
│ │ │ │ ├── utills/
│ │ │ │ │ ├── AlipayZeroSdk.java
│ │ │ │ │ ├── AndroidUtil.java
│ │ │ │ │ ├── DataCleanManager.java
│ │ │ │ │ ├── DateUtil.java
│ │ │ │ │ ├── DisplayUtils.java
│ │ │ │ │ ├── EmojiFilter.java
│ │ │ │ │ ├── ImageUtil.java
│ │ │ │ │ ├── KeyboardUtils.java
│ │ │ │ │ ├── MDTintUtil.java
│ │ │ │ │ ├── PackageUtil.java
│ │ │ │ │ └── StatusBarUtil.java
│ │ │ │ └── widget/
│ │ │ │ ├── AboutDialog.java
│ │ │ │ ├── ObservableWebView.java
│ │ │ │ ├── PinchImageView.java
│ │ │ │ ├── RecycleViewDivider.java
│ │ │ │ ├── SquareLoading.java
│ │ │ │ └── recyclerviewwithfooter/
│ │ │ │ ├── DefaultEmptyItem.java
│ │ │ │ ├── DefaultFootItem.java
│ │ │ │ ├── EmptyItem.java
│ │ │ │ ├── FootItem.java
│ │ │ │ ├── OnLoadMoreListener.java
│ │ │ │ ├── RecyclerViewUtils.java
│ │ │ │ └── RecyclerViewWithFooter.java
│ │ │ └── res/
│ │ │ ├── color/
│ │ │ │ ├── select_press_color_gray.xml
│ │ │ │ └── select_press_color_white.xml
│ │ │ ├── drawable/
│ │ │ │ ├── ic_beauty.xml
│ │ │ │ ├── ic_collection.xml
│ │ │ │ ├── ic_collection_shortcut.xml
│ │ │ │ ├── ic_edit_clear.xml
│ │ │ │ ├── ic_favorite.xml
│ │ │ │ ├── ic_item_author.xml
│ │ │ │ ├── ic_item_label.xml
│ │ │ │ ├── ic_item_time.xml
│ │ │ │ ├── ic_loading.xml
│ │ │ │ ├── ic_right.xml
│ │ │ │ ├── ic_search_gank.xml
│ │ │ │ ├── ic_search_shortcut.xml
│ │ │ │ ├── ic_setting.xml
│ │ │ │ ├── ic_unfavorite.xml
│ │ │ │ ├── ic_webview_finish.xml
│ │ │ │ ├── progressbar.xml
│ │ │ │ ├── selector_history_item.xml
│ │ │ │ ├── shape_corners_gray.xml
│ │ │ │ ├── shape_corners_stroke_gray.xml
│ │ │ │ └── shape_corners_white.xml
│ │ │ ├── layout/
│ │ │ │ ├── activity_bigimg.xml
│ │ │ │ ├── activity_favorite.xml
│ │ │ │ ├── activity_home.xml
│ │ │ │ ├── activity_launcher.xml
│ │ │ │ ├── activity_search.xml
│ │ │ │ ├── activity_setting.xml
│ │ │ │ ├── activity_web_view.xml
│ │ │ │ ├── dialog_about.xml
│ │ │ │ ├── fragment.xml
│ │ │ │ ├── item.xml
│ │ │ │ ├── item_favorite.xml
│ │ │ │ ├── item_history.xml
│ │ │ │ ├── item_search.xml
│ │ │ │ ├── rv_with_footer_empty_layout.xml
│ │ │ │ └── rv_with_footer_loading.xml
│ │ │ ├── menu/
│ │ │ │ └── menu_webview.xml
│ │ │ ├── values/
│ │ │ │ ├── attrs_square_loading.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ ├── values-v19/
│ │ │ │ └── styles.xml
│ │ │ └── xml/
│ │ │ └── shortcuts.xml
│ │ └── test/
│ │ └── java/
│ │ └── me/
│ │ └── bakumon/
│ │ └── ugank/
│ │ └── ExampleUnitTest.java
│ └── ugank.jks
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.iml
.gradle
/local.properties
.DS_Store
/build
/captures
.externalNativeBuild
/.idea/
keystore.properties
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# 「有干货」- 体验别具一格的 Gank.io 安卓客户端

## 下载
去酷安下载:
## 介绍
「有干货」是一款注重体验的 [Gank.io](http://gank.io) 第三方安卓客户端,首页即可随机查看妹子,还能浏览各种类型(App、Android、iOS、前端、瞎推荐、拓展资源等)的干货数据,搜索界面提供妹子福利查看大图功能。App 整体秉承简洁风格。
## 架构
采用 MVP 架构。
参考:[android-architecture#todo-mvp-rxjava](https://github.com/googlesamples/android-architecture/tree/todo-mvp-rxjava)
## 截图

## API
[代码家](https://github.com/daimajia) [干货集中营](http://gank.io/) 提供 API
## License
[GNU General Public License, version 3](https://github.com/Bakumon/UGank/blob/master/LICENSE)
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-cayman
show_downloads: true
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle
================================================
apply plugin: 'com.android.application'
// 加载 keystore.properties 文件
def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
android {
compileSdkVersion ANDROID_BUILD_SDK_VERSION as int
buildToolsVersion ANDROID_BUILD_TOOLS_VERSION
defaultConfig {
applicationId "me.bakumon.ugank"
minSdkVersion ANDROID_BUILD_MIN_SDK_VERSION as int
targetSdkVersion ANDROID_BUILD_TARGET_SDK_VERSION as int
versionCode VERSION_CODE as int
versionName VERSION_NAME
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
signingConfigs {
release {
storeFile file("ugank.jks")
storePassword keystoreProperties['KEYSTORE_PASSWORD']
keyAlias keystoreProperties['KEY_ALIAS']
keyPassword keystoreProperties['KEY_PASSWORD']
}
}
buildTypes {
release {
// 混淆
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// Zipalign优化
zipAlignEnabled true
// 移除无用的resource文件
shrinkResources true
// 签名
signingConfig signingConfigs.release
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
// 输出apk名称为ugank_release_1.0.1_2.apk
def fileName = "ugank_release_${defaultConfig.versionName}_${defaultConfig.versionCode}.apk"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile('com.github.Andy671:Dachshund-Tab-Layout:v0.3.0') {
exclude group: 'com.android.support'
}
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:support-v4:25.1.1'
compile 'com.android.support:design:25.1.1'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.github.florent37:picassopalette:2.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.afollestad.material-dialogs:commons:0.9.3.0'
compile 'cn.bingoogolapple:bga-swipebacklayout:1.0.7@aar'
compile 'org.litepal.android:core:1.5.0'
compile 'com.github.GrenderG:Toasty:1.1.3'
testCompile 'junit:junit:4.12'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
compile 'com.luolc:emoji-rain:0.1.1'
compile 'com.google.android:flexbox:0.3.0-alpha3'
}
================================================
FILE: app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\android\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 *;
#}
#############################################
#
# 对于一些基本指令的添加
#
#############################################
# 代码混淆压缩比,在0~7之间,默认为5,一般不做修改
-optimizationpasses 5
# 混合时不使用大小写混合,混合后的类名为小写
-dontusemixedcaseclassnames
# 指定不去忽略非公共库的类
-dontskipnonpubliclibraryclasses
# 这句话能够使我们的项目混淆后产生映射文件
# 包含有类名->混淆后类名的映射关系
-verbose
# 指定不去忽略非公共库的类成员
-dontskipnonpubliclibraryclassmembers
# 不做预校验,preverify是proguard的四个步骤之一,Android不需要preverify,去掉这一步能够加快混淆速度。
-dontpreverify
# 保留Annotation不混淆
-keepattributes *Annotation*,InnerClasses
# 避免混淆泛型
-keepattributes Signature
# 抛出异常时保留代码行号
-keepattributes SourceFile,LineNumberTable
# 指定混淆是采用的算法,后面的参数是一个过滤器
# 这个过滤器是谷歌推荐的算法,一般不做更改
-optimizations !code/simplification/cast,!field/*,!class/merging/*
#############################################
#
# Android开发中一些需要保留的公共部分
#
#############################################
# 保留我们使用的四大组件,自定义的Application等等这些类不被混淆
# 因为这些子类都有可能被外部调用
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Appliction
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.view.View
-keep public class com.android.vending.licensing.ILicensingService
# 保留support下的所有类及其内部类
-keep class android.support.** {*;}
# 保留继承的
-keep public class * extends android.support.v4.**
-keep public class * extends android.support.v7.**
-keep public class * extends android.support.annotation.**
# 保留R下面的资源
-keep class **.R$* {*;}
# 保留本地native方法不被混淆
-keepclasseswithmembernames class * {
native ;
}
# 保留在Activity中的方法参数是view的方法,
# 这样以来我们在layout中写的onClick就不会被影响
-keepclassmembers class * extends android.app.Activity{
public void *(android.view.View);
}
# 保留枚举类不被混淆
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
# 保留我们自定义控件(继承自View)不被混淆
-keep public class * extends android.view.View{
*** get*();
void set*(***);
public (android.content.Context);
public (android.content.Context, android.util.AttributeSet);
public (android.content.Context, android.util.AttributeSet, int);
}
# 保留Parcelable序列化类不被混淆
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
# 保留Serializable序列化的类不被混淆
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
!static !transient ;
!private ;
!private ;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
# 对于带有回调函数的onXXEvent、**On*Listener的,不能被混淆
-keepclassmembers class * {
void *(**On*Event);
void *(**On*Listener);
}
# webView处理,项目中没有使用到webView忽略即可
-keepclassmembers class fqcn.of.javascript.interface.for.webview {
public *;
}
-keepclassmembers class * extends android.webkit.webViewClient {
public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);
public boolean *(android.webkit.WebView, java.lang.String);
}
-keepclassmembers class * extends android.webkit.webViewClient {
public void *(android.webkit.webView, jav.lang.String);
}
# 移除Log类打印各个等级日志的代码,打正式包的时候可以做为禁log使用,这里可以作为禁止log打印的功能使用
# 记得proguard-android.txt中一定不要加-dontoptimize才起作用
# 另外的一种实现方案是通过BuildConfig.DEBUG的变量来控制
#-assumenosideeffects class android.util.Log {
# public static int v(...);
# public static int i(...);
# public static int w(...);
# public static int d(...);
# public static int e(...);
#}
#############################################
#
# 项目中特殊处理部分
#
#############################################
#-----------处理反射类---------------
#-----------处理js交互---------------
#-----------处理实体类---------------
# 在开发的时候我们可以将所有的实体类放在一个包内,这样我们写一次混淆就行了。
#-keep public class com.ljd.example.entity.** {
# public void set*(***);
# public *** get*();
# public *** is*();
#}
#-----------处理第三方依赖库---------
# AndroidEventBus
-keep class org.simple.** { *; }
-keep interface org.simple.** { *; }
-keepclassmembers class * {
@org.simple.eventbus.Subscriber ;
}
# 百度地图(jar包换成自己的版本,记得签名要匹配)
#-libraryjars libs/baidumapapi_v2_1_3.jar
#-keep class com.baidu.** {*;}
#-keep class vi.com.** {*;}
#-keep class com.sinovoice.** {*;}
#-keep class pvi.com.** {*;}
#-dontwarn com.baidu.**
#-dontwarn vi.com.**
#-dontwarn pvi.com.**
# Bugly
#-dontwarn com.tencent.bugly.**
#-keep class com.tencent.bugly.** {*;}
# ButterKnife
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }
-keepclasseswithmembernames class * {
@butterknife.* ;
}
-keepclasseswithmembernames class * {
@butterknife.* ;
}
# EventBus
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe ;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Facebook
#-keep class com.facebook.** {*;}
#-keep interface com.facebook.** {*;}
#-keep enum com.facebook.** {*;}
# FastJson
#-dontwarn com.alibaba.fastjson.**
#-keep class com.alibaba.fastjson.** { *; }
#-keepattributes Signature
#-keepattributes *Annotation*
# Fresco
#-keep class com.facebook.fresco.** {*;}
#-keep interface com.facebook.fresco.** {*;}
#-keep enum com.facebook.fresco.** {*;}
# 高德相关依赖
# 集合包:3D地图3.3.2 导航1.8.0 定位2.5.0
#-dontwarn com.amap.api.**
#-dontwarn com.autonavi.**
#-keep class com.amap.api.**{*;}
#-keep class com.autonavi.**{*;}
# 地图服务
#-dontwarn com.amap.api.services.**
#-keep class com.map.api.services.** {*;}
# 3D地图
#-dontwarn com.amap.api.mapcore.**
#-dontwarn com.amap.api.maps.**
#-dontwarn com.autonavi.amap.mapcore.**
#-keep class com.amap.api.mapcore.**{*;}
#-keep class com.amap.api.maps.**{*;}
#-keep class com.autonavi.amap.mapcore.**{*;}
# 定位
#-dontwarn com.amap.api.location.**
#-dontwarn com.aps.**
#-keep class com.amap.api.location.**{*;}
#-keep class com.aps.**{*;}
# 导航
#-dontwarn com.amap.api.navi.**
#-dontwarn com.autonavi.**
#-keep class com.amap.api.navi.** {*;}
#-keep class com.autonavi.** {*;}
# Glide
#-keep public class * implements com.bumptech.glide.module.GlideModule
#-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
# **[] $VALUES;
# public *;
#}
### greenDAO 2
#-keepclassmembers class * extends de.greenrobot.dao.AbstractDao {
#public static java.lang.String TABLENAME;
#}
#-keep class **$Properties
### greenDAO 3
#-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
#public static java.lang.String TABLENAME;
#}
#-keep class **$Properties
# If you do not use SQLCipher:
#-dontwarn org.greenrobot.greendao.database.**
# If you do not use RxJava:
#-dontwarn rx.**
# Gson
#-keepattributes Signature-keepattributes *Annotation*
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
# 使用Gson时需要配置Gson的解析对象及变量都不混淆。不然Gson会找不到变量。
# 将下面替换成自己的实体类
-keep class me.bakumon.ugank.entity.** { *; }
# Jackson
#-dontwarn org.codehaus.jackson.**
#-dontwarn com.fasterxml.jackson.databind.**
#-keep class org.codehaus.jackson.** { *;}
#-keep class com.fasterxml.jackson.** { *; }
# 极光推送
#-dontoptimize
#-dontpreverify
#-dontwarn cn.jpush.**
#-keep class cn.jpush.** { *; }
# OkHttp
-keep class com.squareup.okhttp.** { *; }
-keep interface com.squareup.okhttp.** { *; }
-dontwarn com.squareup.okhttp.**
# OkHttp3
-dontwarn com.squareup.okhttp3.**
-keep class com.squareup.okhttp3.** { *;}
-dontwarn okio.**
# Okio
-dontwarn com.squareup.**
-dontwarn okio.**
-keep public class org.codehaus.* { *; }
-keep public class java.nio.* { *; }
# OrmLite
#-keepattributes *DatabaseField*
#-keepattributes *DatabaseTable*
#-keepattributes *SerializedName*
#-keep class com.j256.**
#-keepclassmembers class com.j256.** { *; }
#-keep enum com.j256.**
#-keepclassmembers enum com.j256.** { *; }
#-keep interface com.j256.**
#-keepclassmembers interface com.j256.** { *; }
# Realm
#-keep class io.realm.annotations.RealmModule
#-keep @io.realm.annotations.RealmModule class *
#-keep class io.realm.internal.Keep
#-keep @io.realm.internal.Keep class * { *; }
#-dontwarn javax.**
#-dontwarn io.realm.**
# Retrofit
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions
# Retrolambda
-dontwarn java.lang.invoke.*
# RxJava RxAndroid
-dontwarn sun.misc.**
-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
long producerIndex;
long consumerIndex;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
rx.internal.util.atomic.LinkedQueueNode producerNode;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {
rx.internal.util.atomic.LinkedQueueNode consumerNode;
}
# Universal-Image-Loader-v1.9.5
#-libraryjars libs/universal-image-loader-1.9.5-SNAPSHOT-with-sources.jar
#-dontwarn com.nostra13.universalimageloader.**
#-keep class com.nostra13.universalimageloader.** { *; }
# 微信支付
#-dontwarn com.tencent.mm.**
#-dontwarn com.tencent.wxop.stat.**
#-keep class com.tencent.mm.** {*;}
#-keep class com.tencent.wxop.stat.**{*;}
# 信鸽
#-keep public class * extends android.app.Service
#-keep public class * extends android.content.BroadcastReceiver
#-keep class com.tencent.android.tpush.** {* ;}
#-keep class com.tencent.mid.** {* ;}
#-keepattributes *Annotation*
# 新浪微博
#-keep class com.sina.weibo.sdk.* { *; }
#-keep class android.support.v4.* { *; }
#-keep class com.tencent.* { *; }
#-keep class com.baidu.* { *; }
#-keep class lombok.ast.ecj.* { *; }
#-dontwarn android.support.v4.**
#-dontwarn com.tencent.**s
#-dontwarn com.baidu.**
# 讯飞语音
#-dontwarn com.iflytek.**
#-keep class com.iflytek.** {*;}
# xUtils3.0
#-keepattributes Signature,Annotation
#-keep public class org.xutils.** {
#public protected *;
#}
#-keep public interface org.xutils.** {
#public protected *;
#}
#-keepclassmembers class * extends org.xutils.** {
#public protected *;
#}
#-keepclassmembers @org.xutils.db.annotation.* class * {*;}
#-keepclassmembers @org.xutils.http.annotation. class * {*;}
#-keepclassmembers class * {
#@org.xutils.view.annotation.Event ;
#}
# 银联
#-dontwarn com.unionpay.**
#-keep class com.unionpay.** { *; }
# 友盟统计分析
#-keepclassmembers class * { public (org.json.JSONObject); }
#-keepclassmembers enum com.umeng.analytics.** {
# public static **[] values();
# public static ** valueOf(java.lang.String);
#}
# 友盟自动更新
#-keepclassmembers class * { public (org.json.JSONObject); }
#-keep public class cn.irains.parking.cloud.pub.R$*{ public static final int *; }
#-keep public class * extends com.umeng.**
#-keep class com.umeng.** { *; }
# 支付宝钱包
#-dontwarn com.alipay.**
#-dontwarn HttpUtils.HttpFetcher
#-dontwarn com.ta.utdid2.**
#-dontwarn com.ut.device.**
#-keep class com.alipay.android.app.IAlixPay{*;}
#-keep class com.alipay.android.app.IAlixPay$Stub{*;}
#-keep class com.alipay.android.app.IRemoteServiceCallback{*;}
#-keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
#-keep class com.alipay.sdk.app.PayTask{ public *;}
#-keep class com.alipay.sdk.app.AuthTask{ public *;}
#-keep class com.alipay.mobilesecuritysdk.*
#-keep class com.ut.*
#litepalang
-keep class org.litepal.** {*;}
-keep class * extends org.litepal.crud.DataSupport {*;}
================================================
FILE: app/src/androidTest/java/me/bakumon/ugank/ExampleInstrumentedTest.java
================================================
package me.bakumon.ugank;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see Testing documentation
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("me.bakumon.gank", appContext.getPackageName());
}
}
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/assets/litepal.xml
================================================
================================================
FILE: app/src/main/java/me/bakumon/ugank/App.java
================================================
package me.bakumon.ugank;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import org.litepal.LitePal;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackManager;
//import com.squareup.leakcanary.LeakCanary;
/**
* App
* Created by bakumon on 2016/12/8 17:18.
*/
public class App extends Application {
private static App INSTANCE;
public static App getInstance() {
return INSTANCE;
}
@Override
public void onCreate() {
super.onCreate();
// 初始化 LeakCanary
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
BGASwipeBackManager.getInstance().init(this);
INSTANCE = this;
// 初始化主题色
ThemeManage.INSTANCE.initColorPrimary(getResources().getColor(R.color.colorPrimary));
ConfigManage.INSTANCE.initConfig(this);
LitePal.initialize(this);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/ConfigManage.java
================================================
package me.bakumon.ugank;
import android.content.Context;
import android.content.SharedPreferences;
/**
* ConfigManage
* Created by bakumon on 2016/12/22 15:44.
*/
public enum ConfigManage {
INSTANCE;
private final String spName = "app_config";
private final String key_isListShowImg = "isListShowImg";
private final String key_thumbnailQuality = "thumbnailQuality";
private final String key_banner_url = "keyBannerUrl";
private final String key_launcher_img_show = "keyLauncherImgShow";
private final String key_launcher_img_probability_show = "keyLauncherImgProbabilityShow";
private boolean isListShowImg;
private int thumbnailQuality;
private String bannerURL;
private boolean isShowLauncherImg;
private boolean isProbabilityShowLauncherImg;
public void initConfig(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
// 列表是否显示图片
isListShowImg = sharedPreferences.getBoolean(key_isListShowImg, true);
// 缩略图质量 0:原图 1:默认 2:省流
thumbnailQuality = sharedPreferences.getInt(key_thumbnailQuality, 1);
// Banner URL 用于加载页显示
bannerURL = sharedPreferences.getString(key_banner_url, "");
// 启动页是否显示妹子图
isShowLauncherImg = sharedPreferences.getBoolean(key_launcher_img_show, true);
// 启动页是否概率出现
isProbabilityShowLauncherImg = sharedPreferences.getBoolean(key_launcher_img_probability_show, false);
}
public boolean isListShowImg() {
return isListShowImg;
}
public void setListShowImg(boolean listShowImg) {
SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key_isListShowImg, listShowImg);
if (editor.commit()) {
isListShowImg = listShowImg;
}
}
public int getThumbnailQuality() {
return thumbnailQuality;
}
public void setThumbnailQuality(int thumbnailQuality) {
SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key_thumbnailQuality, thumbnailQuality);
if (editor.commit()) {
this.thumbnailQuality = thumbnailQuality;
}
}
public String getBannerURL() {
return bannerURL;
}
public void setBannerURL(String bannerURL) {
SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key_banner_url, bannerURL);
if (editor.commit()) {
this.bannerURL = bannerURL;
}
}
public boolean isShowLauncherImg() {
return isShowLauncherImg;
}
public void setShowLauncherImg(boolean showLauncherImg) {
SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key_launcher_img_show, showLauncherImg);
if (editor.commit()) {
isShowLauncherImg = showLauncherImg;
}
}
public boolean isProbabilityShowLauncherImg() {
return isProbabilityShowLauncherImg;
}
public void setProbabilityShowLauncherImg(boolean probabilityShowLauncherImg) {
SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key_launcher_img_probability_show, probabilityShowLauncherImg);
if (editor.commit()) {
isProbabilityShowLauncherImg = probabilityShowLauncherImg;
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/GlobalConfig.java
================================================
package me.bakumon.ugank;
/**
* 全局配置
* Created by bakumon on 2016/12/9 14:57.
*/
public class GlobalConfig {
public final static int PAGE_SIZE_CATEGORY = 10;
public final static int PAGE_SIZE_FAVORITE = 10;
public final static String CATEGORY_NAME_APP = "App";
public final static String CATEGORY_NAME_ANDROID = "Android";
public final static String CATEGORY_NAME_IOS = "iOS";
public final static String CATEGORY_NAME_FRONT_END = "前端";
public final static String CATEGORY_NAME_RECOMMEND = "瞎推荐";
public final static String CATEGORY_NAME_RESOURCE = "拓展资源";
public final static String PICASSO_TAG_THUMBNAILS_CATEGORY_LIST_ITEM = "Thumbnails_categoryList_item";
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/ThemeManage.java
================================================
package me.bakumon.ugank;
/**
* ThemeManage
* 主题色管理类
* Created by bakumon on 2016/12/22 15:03.
*/
public enum ThemeManage {
INSTANCE;
private int colorPrimary;
public void initColorPrimary(int colorPrimary) {
setColorPrimary(colorPrimary);
}
public int getColorPrimary() {
return colorPrimary;
}
public void setColorPrimary(int colorPrimary) {
this.colorPrimary = colorPrimary;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/BaseDialog.java
================================================
package me.bakumon.ugank.base;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import butterknife.ButterKnife;
import me.bakumon.ugank.R;
/**
* BaseDialog
* Created by bakumon on 2015/12/28.
*/
public abstract class BaseDialog extends Dialog {
Context mContext;
public BaseDialog(Context context, int layoutId) {
this(context, layoutId, R.style.MyDialog);
}
public BaseDialog(Context context, int layoutId, int styleId) {
super(context, styleId);
this.mContext = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(layoutId, null);
this.setContentView(view);
ButterKnife.bind(this);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/BasePresenter.java
================================================
package me.bakumon.ugank.base;
/**
* BasePresenter
* Created by bakumon on 2016/12/6.
*/
public interface BasePresenter {
void subscribe();
void unsubscribe();
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/BaseView.java
================================================
package me.bakumon.ugank.base;
/**
* BaseView
* Created by bakumon on 2016/12/6.
*/
public interface BaseView {
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/SwipeBackBaseActivity.java
================================================
package me.bakumon.ugank.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import me.bakumon.ugank.R;
/**
* 滑动返回 Base 类
* https://github.com/bingoogolapple/BGASwipeBackLayout-Android
* Created by bakumon on 17-3-5.
*/
public abstract class SwipeBackBaseActivity extends AppCompatActivity implements BGASwipeBackHelper.Delegate {
protected BGASwipeBackHelper mSwipeBackHelper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackManager.getInstance().init(this) 来初始化滑动返回」
// 在 super.onCreate(savedInstanceState) 之前调用该方法
initSwipeBackFinish();
super.onCreate(savedInstanceState);
}
/**
* 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
*/
private void initSwipeBackFinish() {
mSwipeBackHelper = new BGASwipeBackHelper(this, this);
// 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackManager.getInstance().init(this) 来初始化滑动返回」
// 下面几项可以不配置,这里只是为了讲述接口用法。
// 设置滑动返回是否可用。默认值为 true
mSwipeBackHelper.setSwipeBackEnable(true);
// 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
// 设置是否是微信滑动返回样式。默认值为 true
// 选用微信滑动返回样式会有两个问题:
// 1.正在滑动时按下返回键 view 显示异常
// 2. 界面有明显的抖动
mSwipeBackHelper.setIsWeChatStyle(false);
// 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
// 设置是否显示滑动返回的阴影效果。默认值为 true
mSwipeBackHelper.setIsNeedShowShadow(true);
// 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
mSwipeBackHelper.setIsShadowAlphaGradient(true);
}
/**
* 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回,如果某个界面不想支持滑动返回则重写该方法返回 false 即可
*
* @return
*/
@Override
public boolean isSupportSwipeBack() {
return true;
}
/**
* 正在滑动返回
*
* @param slideOffset 从 0 到 1
*/
@Override
public void onSwipeBackLayoutSlide(float slideOffset) {
}
/**
* 没达到滑动返回的阈值,取消滑动返回动作,回到默认状态
*/
@Override
public void onSwipeBackLayoutCancel() {
}
/**
* 滑动返回执行完毕,销毁当前 Activity
*/
@Override
public void onSwipeBackLayoutExecuted() {
mSwipeBackHelper.swipeBackward();
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/adapter/CommonAdapter4RecyclerView.java
================================================
package me.bakumon.ugank.base.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* BaseView
* Created by bakumon on 2016/12/6.
*/
public abstract class CommonAdapter4RecyclerView extends RecyclerView.Adapter {
public Context mContext;
public List mData;
private int layoutId;
private View mView;
public CommonAdapter4RecyclerView(Context context, List data, int layoutId) {
this.mContext = context;
this.mData = data == null ? (List) new ArrayList<>() : data;
this.layoutId = layoutId;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(layoutId, parent, false);
return new CommonHolder4RecyclerView(mView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
CommonHolder4RecyclerView commonHolder = (CommonHolder4RecyclerView) holder;
commonHolder.position = position;
convert(commonHolder, mData.get(position));
}
@Override
public int getItemCount() {
return (mData != null) ? mData.size() : 0;
}
public abstract void convert(CommonHolder4RecyclerView holder, T t);
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/adapter/CommonHolder4RecyclerView.java
================================================
package me.bakumon.ugank.base.adapter;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;
/**
* BaseView
* Created by bakumon on 2016/12/6.
*/
public class CommonHolder4RecyclerView extends RecyclerView.ViewHolder {
public View mConvertView;
public int position;
private SparseArray mViews;
public CommonHolder4RecyclerView(View itemView) {
super(itemView);
this.mConvertView = itemView;
this.mViews = new SparseArray<>();
}
/**
* 得到item上的控件
*
* @param viewId 控件的id
* @return 对应的控件
*/
public T getView(@IdRes int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public CommonHolder4RecyclerView setTextViewText(@IdRes int textViewId, String text) {
TextView tv = getView(textViewId);
if (!TextUtils.isEmpty(text)) {
tv.setText(text);
} else {
tv.setText(" ");
}
return this;
}
public CommonHolder4RecyclerView setOnClickListener(ListenerWithPosition.OnClickWithPositionListener clickListener, @IdRes int... viewIds) {
ListenerWithPosition listener = new ListenerWithPosition(position, this);
listener.setOnClickListener(clickListener);
for (int id : viewIds) {
View v = getView(id);
v.setOnClickListener(listener);
}
return this;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/adapter/CommonViewPagerAdapter.java
================================================
package me.bakumon.ugank.base.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* BaseView
* Created by bakumon on 2016/12/6.
*/
public class CommonViewPagerAdapter extends FragmentPagerAdapter {
private String[] title;
private List mFragments = new ArrayList<>();
public CommonViewPagerAdapter(FragmentManager fm, String[] titles) {
super(fm);
title = titles;
}
public void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/base/adapter/ListenerWithPosition.java
================================================
package me.bakumon.ugank.base.adapter;
import android.view.View;
/**
* ListenerWithPosition
* Created by bakumon on 2016/12/6.
*/
public class ListenerWithPosition implements View.OnClickListener {
private int mPosition;
private Object mHolder;
private OnClickWithPositionListener mOnClickListener;
public ListenerWithPosition(int position, Object holder) {
this.mPosition = position;
this.mHolder = holder;
}
@Override
public void onClick(View v) {
if (mOnClickListener != null)
mOnClickListener.onClick(v, mPosition, mHolder);
}
public interface OnClickWithPositionListener {
void onClick(View v, int position, T holder);
}
public void setOnClickListener(OnClickWithPositionListener mOnClickListener) {
this.mOnClickListener = mOnClickListener;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/entity/CategoryResult.java
================================================
package me.bakumon.ugank.entity;
import java.util.List;
/**
* CategoryResult
* Created by bakumon on 2016/12/8.
*/
public class CategoryResult {
public boolean error;
public List results;
public static class ResultsBean {
public String _id;
public String createdAt;
public String desc;
public String publishedAt;
public String source;
public String type;
public String url;
public boolean used;
public String who;
public List images;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/entity/Favorite.java
================================================
package me.bakumon.ugank.entity;
import org.litepal.crud.DataSupport;
import java.io.Serializable;
/**
* Favorite
* Created by bakumon on 17-3-22.
*/
public class Favorite extends DataSupport implements Serializable{
private String title;
private String type;
private String author;
private String data;
private String url;
private String gankID;
private long createtime;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getGankID() {
return gankID;
}
public void setGankID(String gankID) {
this.gankID = gankID;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/entity/History.java
================================================
package me.bakumon.ugank.entity;
import org.litepal.crud.DataSupport;
/**
* History
* Created by bakumon on 2017/2/18
*/
public class History extends DataSupport {
private long createTimeMill;
private String content;
public long getCreateTimeMill() {
return createTimeMill;
}
public void setCreateTimeMill(long createTimeMill) {
this.createTimeMill = createTimeMill;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/entity/SearchResult.java
================================================
package me.bakumon.ugank.entity;
import java.util.List;
/**
* SearchResult
* Created by bakumon on 2016/12/19 17:00.
*/
public class SearchResult {
public int count;
public boolean error;
public List results;
public static class ResultsBean {
public String desc;
public String ganhuo_id;
public String publishedAt;
public String readability;
public String type;
public String url;
public String who;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/bigimg/BigimgActivity.java
================================================
package me.bakumon.ugank.module.bigimg;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.SwipeBackBaseActivity;
import me.bakumon.ugank.utills.DisplayUtils;
import me.bakumon.ugank.utills.StatusBarUtil;
import me.bakumon.ugank.widget.PinchImageView;
import me.bakumon.ugank.widget.SquareLoading;
public class BigimgActivity extends SwipeBackBaseActivity implements BigimgContract.View {
public static final String MEIZI_URL = "me.bakumon.gank.module.img.BigimgActivity.meizi_url";
public static final String MEIZI_TITLE = "me.bakumon.gank.module.img.BigimgActivity.meizi_title";
@BindView(R.id.tv_title_big_img)
TextView tvTitleBigImg;
@BindView(R.id.toolbar_big_img)
Toolbar toolbarBigImg;
@BindView(R.id.appbar_big_img)
AppBarLayout appbarBigImg;
@BindView(R.id.img_big)
PinchImageView imgBig;
@BindView(R.id.sl_big_img_loading)
SquareLoading mSquareLoading;
private BigimgContract.Presenter mBigimgPresenter = new BigimgPresenter(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_bigimg);
ButterKnife.bind(this);
StatusBarUtil.immersive(this);
StatusBarUtil.setPaddingSmart(this, toolbarBigImg);
setSupportActionBar(toolbarBigImg);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
toolbarBigImg.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mBigimgPresenter.subscribe();
}
@Override
protected void onDestroy() {
super.onDestroy();
mBigimgPresenter.unsubscribe();
}
@Override
public void setMeiziTitle(String title) {
tvTitleBigImg.setText(title);
}
@Override
public void loadMeizuImg(String url) {
Picasso.with(this)
.load(url)
.into(imgBig, new Callback() {
@Override
public void onSuccess() {
// 这里可能会有内存泄露
hideLoading();
}
@Override
public void onError() {
}
});
}
@Override
public void setToolbarBackgroundColor(int color) {
appbarBigImg.setBackgroundColor(color);
}
@Override
public void setLoadingColor(int color) {
mSquareLoading.setSquareColor(color);
}
@Override
public void showLoading() {
mSquareLoading.setVisibility(View.VISIBLE);
}
@Override
public String getMeiziImg() {
Bundle bundle = getIntent().getExtras();
return bundle.getString(BigimgActivity.MEIZI_URL);
}
@Override
public String getMeiziTitle() {
Bundle bundle = getIntent().getExtras();
return bundle.getString(BigimgActivity.MEIZI_TITLE);
}
public void hideLoading() {
mSquareLoading.setVisibility(View.GONE);
/*
* 由于 mSquareLoading 持有 Activity Context 引用,在 Picasso 的 Callback 匿名内部类中使用可能会
* 发生内存泄露
*
* 因为 mSquareLoading 不在使用,所有直接置空,否则选择静态内部类和弱引用的方式避免内存泄露
* */
mSquareLoading = null;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/bigimg/BigimgContract.java
================================================
package me.bakumon.ugank.module.bigimg;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
/**
* BigimgContract
* Created by bakumon on 16-12-20.
*/
public interface BigimgContract {
interface View extends BaseView {
void setMeiziTitle(String title);
void loadMeizuImg(String url);
void setToolbarBackgroundColor(int color);
void setLoadingColor(int color);
void showLoading();
String getMeiziImg();
String getMeiziTitle();
}
interface Presenter extends BasePresenter {
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/bigimg/BigimgPresenter.java
================================================
package me.bakumon.ugank.module.bigimg;
import android.support.annotation.NonNull;
import me.bakumon.ugank.ThemeManage;
/**
* BigimgPresenter
* Created by bakumon on 16-12-20.
*/
public class BigimgPresenter implements BigimgContract.Presenter {
private BigimgContract.View mBigimgView;
public BigimgPresenter(@NonNull BigimgContract.View bigimgView) {
mBigimgView = bigimgView;
}
@Override
public void subscribe() {
mBigimgView.setToolbarBackgroundColor(ThemeManage.INSTANCE.getColorPrimary());
mBigimgView.setLoadingColor(ThemeManage.INSTANCE.getColorPrimary());
loadMeiziImg(mBigimgView.getMeiziImg());
setMeiziTitle(mBigimgView.getMeiziTitle());
}
@Override
public void unsubscribe() {
}
private void loadMeiziImg(String url) {
if (url == null) {
return;
}
mBigimgView.showLoading();
mBigimgView.loadMeizuImg(url);
}
private void setMeiziTitle(String title) {
if (title == null) {
return;
}
mBigimgView.setMeiziTitle("妹子:" + title);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/category/CategoryContract.java
================================================
package me.bakumon.ugank.module.category;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
import me.bakumon.ugank.entity.CategoryResult;
/**
* CategoryContract
* Created by bakumon on 2016/12/8.
*/
public interface CategoryContract {
interface View extends BaseView {
void setCategoryItems(CategoryResult categoryResult);
void addCategoryItems(CategoryResult categoryResult);
void getCategoryItemsFail(String failMessage);
String getCategoryName();
void showSwipeLoading();
void hideSwipeLoading();
void setLoading();
}
interface Presenter extends BasePresenter {
void getCategoryItems(boolean isRefresh);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/category/CategoryFragment.java
================================================
package me.bakumon.ugank.module.category;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.GlobalConfig;
import me.bakumon.ugank.R;
import me.bakumon.ugank.entity.CategoryResult;
import me.bakumon.ugank.module.home.HomeActivity;
import me.bakumon.ugank.widget.RecycleViewDivider;
import me.bakumon.ugank.widget.recyclerviewwithfooter.OnLoadMoreListener;
import me.bakumon.ugank.widget.recyclerviewwithfooter.RecyclerViewWithFooter;
import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
/**
* CategoryFragment
* Created by bakumon on 2016/12/8.
*/
public class CategoryFragment extends Fragment implements CategoryContract.View, SwipeRefreshLayout.OnRefreshListener, OnLoadMoreListener {
public static final String CATEGORY_NAME = "me.bakumon.ugank.module.category.CATEGORY_NAME";
@BindView(R.id.recycler_view)
RecyclerViewWithFooter mRecyclerView;
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout mSwipeRefreshLayout;
private CategoryListAdapter mCategoryListAdapter;
private CategoryContract.Presenter mPresenter = new CategoryPresenter(this);
private String mCategoryName;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
mCategoryName = bundle.getString(CATEGORY_NAME);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == HomeActivity.SETTING_REQUEST_CODE) {
mCategoryListAdapter.notifyDataSetChanged();
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
ButterKnife.bind(this, view);
mSwipeRefreshLayout.setColorSchemeResources(
R.color.colorSwipeRefresh1,
R.color.colorSwipeRefresh2,
R.color.colorSwipeRefresh3,
R.color.colorSwipeRefresh4,
R.color.colorSwipeRefresh5,
R.color.colorSwipeRefresh6);
mSwipeRefreshLayout.setOnRefreshListener(this);
mCategoryListAdapter = new CategoryListAdapter(getContext());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL));
mRecyclerView.setAdapter(mCategoryListAdapter);
mRecyclerView.setOnLoadMoreListener(this);
mRecyclerView.setEmpty();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
final Picasso picasso = Picasso.with(CategoryFragment.this.getContext());
if (newState == SCROLL_STATE_IDLE) {
picasso.resumeTag(GlobalConfig.PICASSO_TAG_THUMBNAILS_CATEGORY_LIST_ITEM);
} else {
picasso.pauseTag(GlobalConfig.PICASSO_TAG_THUMBNAILS_CATEGORY_LIST_ITEM);
}
}
});
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPresenter.subscribe();
}
@Override
public void onDestroy() {
super.onDestroy();
Picasso.with(CategoryFragment.this.getContext()).cancelTag(GlobalConfig.PICASSO_TAG_THUMBNAILS_CATEGORY_LIST_ITEM);
mPresenter.unsubscribe();
}
public static CategoryFragment newInstance(String mCategoryName) {
CategoryFragment categoryFragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString(CATEGORY_NAME, mCategoryName);
categoryFragment.setArguments(bundle);
return categoryFragment;
}
@Override
public String getCategoryName() {
return this.mCategoryName;
}
@Override
public void showSwipeLoading() {
mSwipeRefreshLayout.setRefreshing(true);
}
@Override
public void hideSwipeLoading() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onRefresh() {
mPresenter.getCategoryItems(true);
}
@Override
public void onLoadMore() {
mPresenter.getCategoryItems(false);
}
@Override
public void setLoading() {
mRecyclerView.setLoading();
}
@Override
public void getCategoryItemsFail(String failMessage) {
if (getUserVisibleHint()) {
Toasty.error(this.getContext(), failMessage).show();
}
}
@Override
public void setCategoryItems(CategoryResult categoryResult) {
mCategoryListAdapter.mData = categoryResult.results;
mCategoryListAdapter.notifyDataSetChanged();
}
@Override
public void addCategoryItems(CategoryResult categoryResult) {
int start = mCategoryListAdapter.getItemCount();
mCategoryListAdapter.mData.addAll(categoryResult.results);
mCategoryListAdapter.notifyItemRangeInserted(start, categoryResult.results.size());
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/category/CategoryListAdapter.java
================================================
package me.bakumon.ugank.module.category;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.AppCompatImageView;
import android.view.View;
import com.squareup.picasso.Picasso;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.ConfigManage;
import me.bakumon.ugank.GlobalConfig;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.adapter.CommonAdapter4RecyclerView;
import me.bakumon.ugank.base.adapter.CommonHolder4RecyclerView;
import me.bakumon.ugank.base.adapter.ListenerWithPosition;
import me.bakumon.ugank.entity.CategoryResult;
import me.bakumon.ugank.entity.Favorite;
import me.bakumon.ugank.module.webview.WebViewActivity;
import me.bakumon.ugank.utills.DateUtil;
/**
* CategoryListAdapter
* Created by bakumon on 2016/10/13.
*/
public class CategoryListAdapter extends CommonAdapter4RecyclerView implements ListenerWithPosition.OnClickWithPositionListener {
public CategoryListAdapter(Context context) {
super(context, null, R.layout.item);
}
@Override
public void convert(CommonHolder4RecyclerView holder, CategoryResult.ResultsBean androidResult) {
if (androidResult != null) {
AppCompatImageView imageView = holder.getView(R.id.iv_item_img);
if (ConfigManage.INSTANCE.isListShowImg()) { // 列表显示图片
imageView.setVisibility(View.VISIBLE);
String quality = "";
if (androidResult.images != null && androidResult.images.size() > 0) {
switch (ConfigManage.INSTANCE.getThumbnailQuality()) {
case 0: // 原图
quality = "?imageView2/0/w/400";
break;
case 1: // 默认
quality = "?imageView2/0/w/280";
break;
case 2: // 省流
quality = "?imageView2/0/w/190";
break;
}
imageView.setVisibility(View.VISIBLE);
// Picasso.with(mContext).setIndicatorsEnabled(true);//显示指示器
Picasso.with(mContext)
.load(androidResult.images.get(0) + quality)
.placeholder(R.mipmap.image_default)
.tag(GlobalConfig.PICASSO_TAG_THUMBNAILS_CATEGORY_LIST_ITEM)
.centerCrop()
.fit()
.config(Bitmap.Config.RGB_565)
.into(imageView);
} else { // 图片 URL 不存在
imageView.setVisibility(View.GONE);
}
} else { // 列表不显示图片
imageView.setVisibility(View.GONE);
}
holder.setTextViewText(R.id.tv_item_title, androidResult.desc == null ? "unknown" : androidResult.desc);
holder.setTextViewText(R.id.tv_item_publisher, androidResult.who == null ? "unknown" : androidResult.who);
holder.setTextViewText(R.id.tv_item_time, DateUtil.dateFormat(androidResult.publishedAt));
holder.setOnClickListener(this, R.id.ll_item);
}
}
@Override
public void onClick(View v, int position, CommonHolder4RecyclerView holder) {
if (mData == null || mData.get(position) == null) {
Toasty.error(mContext, "数据异常").show();
return;
}
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra(WebViewActivity.GANK_TITLE, mData.get(position).desc);
intent.putExtra(WebViewActivity.GANK_URL, mData.get(position).url);
Favorite favorite = new Favorite();
favorite.setAuthor(mData.get(position).who);
favorite.setData(mData.get(position).publishedAt);
favorite.setTitle(mData.get(position).desc);
favorite.setType(mData.get(position).type);
favorite.setUrl(mData.get(position).url);
favorite.setGankID(mData.get(position)._id);
intent.putExtra(WebViewActivity.FAVORITE_DATA, favorite);
mContext.startActivity(intent);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/category/CategoryPresenter.java
================================================
package me.bakumon.ugank.module.category;
import android.support.annotation.NonNull;
import me.bakumon.ugank.GlobalConfig;
import me.bakumon.ugank.entity.CategoryResult;
import me.bakumon.ugank.network.NetWork;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
/**
* CategoryPresenter
* Created by bakumon on 2016/12/8 16:42.
*/
public class CategoryPresenter implements CategoryContract.Presenter {
private CategoryContract.View mCategoryView;
private int mPage = 1;
@NonNull
private CompositeSubscription mSubscriptions;
public CategoryPresenter(CategoryContract.View androidView) {
mCategoryView = androidView;
mSubscriptions = new CompositeSubscription();
}
@Override
public void subscribe() {
getCategoryItems(true);
}
@Override
public void unsubscribe() {
mSubscriptions.clear();
}
@Override
public void getCategoryItems(final boolean isRefresh) {
if (isRefresh) {
mCategoryView.showSwipeLoading();
mPage = 1;
} else {
mPage += 1;
}
Subscription subscription = NetWork.getGankApi()
.getCategoryDate(mCategoryView.getCategoryName(), GlobalConfig.PAGE_SIZE_CATEGORY, mPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
mCategoryView.hideSwipeLoading();
mCategoryView.getCategoryItemsFail(mCategoryView.getCategoryName() + " 列表数据获取失败。");
}
@Override
public void onNext(CategoryResult androidResult) {
if (isRefresh) {
mCategoryView.setCategoryItems(androidResult);
mCategoryView.hideSwipeLoading();
mCategoryView.setLoading();
} else {
mCategoryView.addCategoryItems(androidResult);
}
}
});
mSubscriptions.add(subscription);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/favorite/FavoriteActivity.java
================================================
package me.bakumon.ugank.module.favorite;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.SwipeBackBaseActivity;
import me.bakumon.ugank.entity.Favorite;
import me.bakumon.ugank.utills.DisplayUtils;
import me.bakumon.ugank.utills.StatusBarUtil;
import me.bakumon.ugank.widget.RecycleViewDivider;
import me.bakumon.ugank.widget.recyclerviewwithfooter.OnLoadMoreListener;
import me.bakumon.ugank.widget.recyclerviewwithfooter.RecyclerViewWithFooter;
public class FavoriteActivity extends SwipeBackBaseActivity implements FavoriteContract.View, OnLoadMoreListener {
@BindView(R.id.toolbar_favorite)
Toolbar mToolbarFavorite;
@BindView(R.id.appbar_favorite)
AppBarLayout mAppbarFavorite;
@BindView(R.id.recycler_view_favorite)
RecyclerViewWithFooter mRecyclerView;
public static final int REQUEST_CODE_FAVORITE = 101;
public static final String FAVORITE_POSITION = "me.bakumon.ugank.module.favorite.FavoriteActivity.favorite_position";
private FavoriteContract.Presenter mPresenter = new FavoritePresenter(this);
private FavoriteListAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_favorite);
ButterKnife.bind(this);
StatusBarUtil.immersive(this);
StatusBarUtil.setPaddingSmart(this, mToolbarFavorite);
setSupportActionBar(mToolbarFavorite);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
initView();
mPresenter.subscribe();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_FAVORITE) {
int position = data.getIntExtra(FAVORITE_POSITION, -1);
if (position != -1) {
mAdapter.notifyItemRemoved(position);
mAdapter.mData.remove(position);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.unsubscribe();
}
private void initView() {
mToolbarFavorite.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mAdapter = new FavoriteListAdapter(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnLoadMoreListener(this);
mRecyclerView.setEmpty();
}
@Override
public void setToolbarBackgroundColor(int color) {
mAppbarFavorite.setBackgroundColor(color);
}
@Override
public void addFavoriteItems(List favorites) {
int start = mAdapter.getItemCount();
mAdapter.mData.addAll(favorites);
mAdapter.notifyItemRangeInserted(start, favorites.size());
}
@Override
public void setFavoriteItems(List favorites) {
mAdapter.mData = favorites;
mAdapter.notifyDataSetChanged();
}
@Override
public void setLoading() {
mRecyclerView.setLoading();
}
@Override
public void setEmpty() {
mRecyclerView.setEmpty();
Toasty.info(this, "暂无收藏").show();
}
@Override
public void setLoadMoreIsLastPage() {
mRecyclerView.setEnd("没有更多数据了");
}
@Override
public void onLoadMore() {
mPresenter.getFavoriteItems(false);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/favorite/FavoriteContract.java
================================================
package me.bakumon.ugank.module.favorite;
import java.util.List;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
import me.bakumon.ugank.entity.Favorite;
/**
* FavoriteContract
* Created by bakumon on 17-3-22.
*/
public class FavoriteContract {
interface View extends BaseView {
void setToolbarBackgroundColor(int color);
void addFavoriteItems(List favorites);
void setFavoriteItems(List favorites);
void setLoading();
void setEmpty();
void setLoadMoreIsLastPage();
}
interface Presenter extends BasePresenter {
void getFavoriteItems(boolean isRefresh);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/favorite/FavoriteListAdapter.java
================================================
package me.bakumon.ugank.module.favorite;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.adapter.CommonAdapter4RecyclerView;
import me.bakumon.ugank.base.adapter.CommonHolder4RecyclerView;
import me.bakumon.ugank.base.adapter.ListenerWithPosition;
import me.bakumon.ugank.entity.Favorite;
import me.bakumon.ugank.module.webview.WebViewActivity;
import me.bakumon.ugank.utills.DateUtil;
/**
* FavoriteListAdapter
* Created by bakumon on 2016/12/20.
*/
public class FavoriteListAdapter extends CommonAdapter4RecyclerView implements ListenerWithPosition.OnClickWithPositionListener {
public FavoriteListAdapter(Context context) {
super(context, null, R.layout.item_favorite);
}
@Override
public void convert(CommonHolder4RecyclerView holder, Favorite favorite) {
if (favorite != null) {
holder.setTextViewText(R.id.tv_item_title_favorite, favorite.getTitle() == null ? "unknown" : favorite.getTitle());
holder.setTextViewText(R.id.tv_item_type_favorite, favorite.getType() == null ? "unknown" : favorite.getType());
holder.setTextViewText(R.id.tv_item_publisher_favorite, favorite.getAuthor() == null ? "unknown" : favorite.getAuthor());
holder.setTextViewText(R.id.tv_item_time_favorite, DateUtil.dateFormat(favorite.getData()));
holder.setOnClickListener(this, R.id.ll_item_favorite);
}
}
@Override
public void onClick(View v, int position, CommonHolder4RecyclerView holder) {
// 通过 notifyRemoveItem 方法移除 item 后,不能使用这个 position
position = holder.getAdapterPosition();
if (mData == null || mData.get(position) == null) {
Toasty.error(mContext, "数据异常").show();
return;
}
Intent intent = new Intent();
intent.setClass(mContext, WebViewActivity.class);
intent.putExtra(WebViewActivity.GANK_TITLE, mData.get(position).getTitle());
intent.putExtra(WebViewActivity.GANK_URL, mData.get(position).getUrl());
intent.putExtra(WebViewActivity.FAVORITE_POSITION, position);
intent.putExtra(WebViewActivity.FAVORITE_DATA, mData.get(position));
((Activity) mContext).startActivityForResult(intent, FavoriteActivity.REQUEST_CODE_FAVORITE);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/favorite/FavoritePresenter.java
================================================
package me.bakumon.ugank.module.favorite;
import org.litepal.crud.DataSupport;
import java.util.List;
import me.bakumon.ugank.GlobalConfig;
import me.bakumon.ugank.ThemeManage;
import me.bakumon.ugank.entity.Favorite;
/**
* FavoritePresenter
* Created by bakumon on 17-3-22.
*/
public class FavoritePresenter implements FavoriteContract.Presenter {
private FavoriteContract.View mView;
private int mPage = 0;
public FavoritePresenter(FavoriteContract.View view) {
mView = view;
}
@Override
public void subscribe() {
mView.setToolbarBackgroundColor(ThemeManage.INSTANCE.getColorPrimary());
getFavoriteItems(true);
}
@Override
public void unsubscribe() {
}
@Override
public void getFavoriteItems(boolean isRefresh) {
if (isRefresh) {
mPage = 0;
} else {
mPage += 1;
}
List favoriteList = DataSupport
.limit(GlobalConfig.PAGE_SIZE_FAVORITE)
.offset(GlobalConfig.PAGE_SIZE_FAVORITE * mPage)
.order("createTime desc")
.find(Favorite.class);
if (isRefresh) {
mView.setFavoriteItems(favoriteList);
mView.setLoading();
if (favoriteList == null || favoriteList.size() < 1) {
mView.setEmpty();
return;
}
} else {
mView.addFavoriteItems(favoriteList);
}
boolean isLastPage = favoriteList.size() < GlobalConfig.PAGE_SIZE_FAVORITE;
if (isLastPage) {
mView.setLoadMoreIsLastPage();
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/home/HomeActivity.java
================================================
package me.bakumon.ugank.module.home;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import com.github.florent37.picassopalette.PicassoPalette;
import com.kekstudio.dachshundtablayout.DachshundTabLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.GlobalConfig;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.adapter.CommonViewPagerAdapter;
import me.bakumon.ugank.module.bigimg.BigimgActivity;
import me.bakumon.ugank.module.category.CategoryFragment;
import me.bakumon.ugank.module.favorite.FavoriteActivity;
import me.bakumon.ugank.module.search.SearchActivity;
import me.bakumon.ugank.module.setting.SettingActivity;
import me.bakumon.ugank.utills.DisplayUtils;
import me.bakumon.ugank.utills.MDTintUtil;
import me.bakumon.ugank.utills.StatusBarUtil;
/**
* HomeActivity
* Created by bakumon on 2016/12/8 16:42.
*/
public class HomeActivity extends AppCompatActivity implements HomeContract.View {
@BindView(R.id.fab_home_random)
FloatingActionButton mFloatingActionButton;
@BindView(R.id.appbar)
AppBarLayout mAppBarLayout;
@BindView(R.id.iv_home_banner)
ImageView mIvHomeBanner;
@BindView(R.id.tab_home_category)
DachshundTabLayout mDachshundTabLayout;
@BindView(R.id.vp_home_category)
ViewPager mVpCategory;
@BindView(R.id.collapsing_toolbar)
CollapsingToolbarLayout mCollapsingToolbar;
@BindView(R.id.tl_home_toolbar)
Toolbar mToolbar;
@BindView(R.id.iv_home_setting)
AppCompatImageView mIvSetting;
private HomeContract.Presenter mHomePresenter = new HomePresenter(this);
public final static int SETTING_REQUEST_CODE = 101;
private CategoryFragment appFragment;
private CategoryFragment androidFragment;
private CategoryFragment iOSFragment;
private CategoryFragment frontFragment;
private CategoryFragment referenceFragment;
private CategoryFragment resFragment;
private String mImgUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
initView();
mHomePresenter.subscribe();
}
@Override
protected void onDestroy() {
super.onDestroy();
mHomePresenter.unsubscribe();
}
private void initView() {
StatusBarUtil.immersive(this);
StatusBarUtil.setPaddingSmart(this, mIvHomeBanner);
StatusBarUtil.setPaddingSmart(this, mToolbar);
setFabDynamicState();
String[] titles = {
GlobalConfig.CATEGORY_NAME_APP,
GlobalConfig.CATEGORY_NAME_ANDROID,
GlobalConfig.CATEGORY_NAME_IOS,
GlobalConfig.CATEGORY_NAME_FRONT_END,
GlobalConfig.CATEGORY_NAME_RECOMMEND,
GlobalConfig.CATEGORY_NAME_RESOURCE};
CommonViewPagerAdapter infoPagerAdapter = new CommonViewPagerAdapter(getSupportFragmentManager(), titles);
// App
appFragment = CategoryFragment.newInstance(titles[0]);
// Android
androidFragment = CategoryFragment.newInstance(titles[1]);
// iOS
iOSFragment = CategoryFragment.newInstance(titles[2]);
// 前端
frontFragment = CategoryFragment.newInstance(titles[3]);
// 瞎推荐
referenceFragment = CategoryFragment.newInstance(titles[4]);
// 拓展资源s
resFragment = CategoryFragment.newInstance(titles[5]);
infoPagerAdapter.addFragment(appFragment);
infoPagerAdapter.addFragment(androidFragment);
infoPagerAdapter.addFragment(iOSFragment);
infoPagerAdapter.addFragment(frontFragment);
infoPagerAdapter.addFragment(referenceFragment);
infoPagerAdapter.addFragment(resFragment);
mVpCategory.setAdapter(infoPagerAdapter);
mDachshundTabLayout.setupWithViewPager(mVpCategory);
mVpCategory.setCurrentItem(1);
}
/**
* CollapsingToolbarLayout 折叠状态
*/
private CollapsingToolbarLayoutState state;
private enum CollapsingToolbarLayoutState {
/**
* 完全展开
*/
EXPANDED,
/**
* 折叠
*/
COLLAPSED,
/**
* 中间状态
*/
INTERNEDIATE
}
/**
* 根据 CollapsingToolbarLayout 的折叠状态,设置 FloatingActionButton 的隐藏和显示
*/
private void setFabDynamicState() {
mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset == 0) {
if (state != CollapsingToolbarLayoutState.EXPANDED) {
// 修改状态标记为展开
state = CollapsingToolbarLayoutState.EXPANDED;
}
} else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
if (state != CollapsingToolbarLayoutState.COLLAPSED) {
mFloatingActionButton.hide();
// 修改状态标记为折叠
state = CollapsingToolbarLayoutState.COLLAPSED;
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
layoutParams.height = DisplayUtils.dp2px(240, HomeActivity.this);
mAppBarLayout.setLayoutParams(layoutParams);
}
} else {
if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
if (state == CollapsingToolbarLayoutState.COLLAPSED) {
mFloatingActionButton.show();
}
// 修改状态标记为中间
state = CollapsingToolbarLayoutState.INTERNEDIATE;
}
}
}
});
}
@OnClick(R.id.ll_home_search)
public void search(View view) {
startActivity(new Intent(HomeActivity.this, SearchActivity.class));
}
@Override
public void showBannerFail(String failMessage) {
Toasty.error(this, failMessage).show();
}
@Override
public void setBanner(String imgUrl) {
mImgUrl = imgUrl;
Picasso.with(this).load(imgUrl)
.into(mIvHomeBanner,
PicassoPalette.with(imgUrl, mIvHomeBanner)
.intoCallBack(new PicassoPalette.CallBack() {
@Override
public void onPaletteLoaded(Palette palette) {
mHomePresenter.setThemeColor(palette);
}
}));
}
@Override
public void cacheImg(final String imgUrl) {
// 预加载 提前缓存好的欢迎图
Picasso.with(this).load(imgUrl).fetch(new Callback() {
@Override
public void onSuccess() {
mHomePresenter.saveCacheImgUrl(imgUrl);
}
@Override
public void onError() {
}
});
}
@Override
public void setAppBarLayoutColor(int appBarLayoutColor) {
mCollapsingToolbar.setContentScrimColor(appBarLayoutColor);
mAppBarLayout.setBackgroundColor(appBarLayoutColor);
}
@Override
public void setFabButtonColor(int color) {
MDTintUtil.setTint(mFloatingActionButton, color);
}
private ObjectAnimator mAnimator;
@Override
public void startBannerLoadingAnim() {
mFloatingActionButton.setImageResource(R.drawable.ic_loading);
mAnimator = ObjectAnimator.ofFloat(mFloatingActionButton, "rotation", 0, 360);
mAnimator.setRepeatCount(ValueAnimator.INFINITE);
mAnimator.setDuration(800);
mAnimator.setInterpolator(new LinearInterpolator());
mAnimator.start();
}
@Override
public void stopBannerLoadingAnim() {
mFloatingActionButton.setImageResource(R.drawable.ic_beauty);
mAnimator.cancel();
mFloatingActionButton.setRotation(0);
}
@Override
public void enableFabButton() {
mFloatingActionButton.setEnabled(true);
}
@Override
public void disEnableFabButton() {
mFloatingActionButton.setEnabled(false);
}
@OnClick(R.id.fab_home_random)
public void random(View view) {
mHomePresenter.getRandomBanner();
}
@OnClick(R.id.iv_home_collection)
public void collection() {
startActivity(new Intent(HomeActivity.this, FavoriteActivity.class));
}
@OnClick(R.id.iv_home_setting)
public void goSetting() {
startActivityForResult(new Intent(HomeActivity.this, SettingActivity.class), SETTING_REQUEST_CODE);
}
@OnClick(R.id.iv_home_banner)
public void goBigImg() {
if (TextUtils.isEmpty(mImgUrl)) {
return;
}
Intent intent = new Intent();
intent.setClass(this, BigimgActivity.class);
intent.putExtra(BigimgActivity.MEIZI_TITLE, "");
intent.putExtra(BigimgActivity.MEIZI_URL, mImgUrl);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (mVpCategory.getCurrentItem()) {
case 0:
appFragment.onActivityResult(requestCode, resultCode, data);
break;
case 1:
androidFragment.onActivityResult(requestCode, resultCode, data);
break;
case 2:
iOSFragment.onActivityResult(requestCode, resultCode, data);
break;
case 3:
frontFragment.onActivityResult(requestCode, resultCode, data);
break;
case 4:
referenceFragment.onActivityResult(requestCode, resultCode, data);
break;
case 5:
resFragment.onActivityResult(requestCode, resultCode, data);
break;
default:
break;
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/home/HomeContract.java
================================================
package me.bakumon.ugank.module.home;
import android.support.annotation.Nullable;
import android.support.v7.graphics.Palette;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
/**
* HomeContract
* Created by bakumon on 2016/12/6 10:48.
*/
public interface HomeContract {
interface View extends BaseView {
void showBannerFail(String failMessage);
void setBanner(String imgUrl);
void cacheImg(String imgUrl);
void startBannerLoadingAnim();
void stopBannerLoadingAnim();
void enableFabButton();
void disEnableFabButton();
void setAppBarLayoutColor(int appBarLayoutColor);
void setFabButtonColor(int color);
}
interface Presenter extends BasePresenter {
void getRandomBanner();
void setThemeColor(@Nullable Palette palette);
void getBanner(final boolean isRandom);
void saveCacheImgUrl(String url);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/home/HomePresenter.java
================================================
package me.bakumon.ugank.module.home;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.graphics.Palette;
import me.bakumon.ugank.App;
import me.bakumon.ugank.ConfigManage;
import me.bakumon.ugank.R;
import me.bakumon.ugank.ThemeManage;
import me.bakumon.ugank.entity.CategoryResult;
import me.bakumon.ugank.network.NetWork;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
/**
* HomePresenter
* Created by bakumon on 2016/12/6 11:07.
*/
public class HomePresenter implements HomeContract.Presenter {
private HomeContract.View mHomeView;
@NonNull
private CompositeSubscription mSubscriptions;
public HomePresenter(HomeContract.View homeView) {
mHomeView = homeView;
mSubscriptions = new CompositeSubscription();
}
@Override
public void subscribe() {
getBanner(false);
cacheRandomImg();
}
@Override
public void unsubscribe() {
mSubscriptions.clear();
}
@Override
public void getRandomBanner() {
getBanner(true);
}
@Override
public void setThemeColor(@Nullable Palette palette) {
if (palette != null) {
int colorPrimary = App.getInstance().getResources().getColor(R.color.colorPrimary);
// 把从调色板上获取的主题色保存在内存中
ThemeManage.INSTANCE.setColorPrimary(palette.getDarkVibrantColor(colorPrimary));
// 设置 AppBarLayout 的背景色
mHomeView.setAppBarLayoutColor(ThemeManage.INSTANCE.getColorPrimary());
// 设置 FabButton 的背景色
mHomeView.setFabButtonColor(ThemeManage.INSTANCE.getColorPrimary());
// 停止 FabButton 加载中动画
mHomeView.enableFabButton();
mHomeView.stopBannerLoadingAnim();
}
}
private void cacheRandomImg() {
if (!ConfigManage.INSTANCE.isShowLauncherImg()) { // 不显示欢迎妹子,也就不需要预加载了
return;
}
if (ConfigManage.INSTANCE.isProbabilityShowLauncherImg()) { // 概率出现欢迎妹子
if (Math.random() < 0.75) {
ConfigManage.INSTANCE.setBannerURL("");
return;
}
}
Observable observable;
observable = NetWork.getGankApi().getRandomBeauties(1);
Subscription subscription = observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(CategoryResult meiziResult) {
if (meiziResult != null && meiziResult.results != null && meiziResult.results.size() > 0 && meiziResult.results.get(0).url != null) {
mHomeView.cacheImg(meiziResult.results.get(0).url);
}
}
});
mSubscriptions.add(subscription);
}
@Override
public void saveCacheImgUrl(String url) {
ConfigManage.INSTANCE.setBannerURL(url);
}
/**
* 或单张 Banner
*
* @param isRandom true:随机 false:获取最新
*/
@Override
public void getBanner(final boolean isRandom) {
mHomeView.startBannerLoadingAnim();
mHomeView.disEnableFabButton();
Observable observable;
if (isRandom) {
observable = NetWork.getGankApi().getRandomBeauties(1);
} else {
observable = NetWork.getGankApi().getCategoryDate("福利", 1, 1);
}
Subscription subscription = observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
mHomeView.showBannerFail("Banner 图加载失败。");
mHomeView.enableFabButton();
mHomeView.stopBannerLoadingAnim();
}
@Override
public void onNext(CategoryResult meiziResult) {
if (meiziResult != null && meiziResult.results != null && meiziResult.results.size() > 0 && meiziResult.results.get(0).url != null) {
mHomeView.setBanner(meiziResult.results.get(0).url);
} else {
mHomeView.showBannerFail("Banner 图加载失败。");
}
}
});
mSubscriptions.add(subscription);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/launcher/LauncherActivity.java
================================================
package me.bakumon.ugank.module.launcher;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.bakumon.ugank.R;
import me.bakumon.ugank.module.bigimg.BigimgActivity;
import me.bakumon.ugank.module.home.HomeActivity;
/**
* LauncherActivity
* Created by bakumon on 2016/12/8.
*/
public class LauncherActivity extends AppCompatActivity implements LauncherContract.View {
@BindView(R.id.img_launcher_welcome)
AppCompatImageView mImageView;
// 记录该 Activity 是否在前台显示
private boolean isResume;
private String mUrl;
private LauncherContract.Presenter mLauncherPresenter = new LauncherPresenter(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_launcher);
ButterKnife.bind(this);
mLauncherPresenter.subscribe();
}
@Override
public void loadImg(String url) {
mUrl = url;
try {
Picasso.with(this)
.load(url)
.into(mImageView, new Callback() {
@Override
public void onSuccess() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (!isResume) {
finish();
return;
}
goHomeActivity();
}
}, 1200);
}
@Override
public void onError() {
goHomeActivity();
}
});
} catch (Exception e) {
goHomeActivity();
}
}
@Override
protected void onResume() {
super.onResume();
isResume = true;
}
@Override
protected void onPause() {
super.onPause();
isResume = false;
}
@Override
public void goHomeActivity() {
Intent intent = new Intent(LauncherActivity.this, HomeActivity.class);
startActivity(intent);
// Activity 切换淡入淡出动画
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
@OnClick(R.id.img_launcher_welcome)
public void goBigImg(){
if (TextUtils.isEmpty(mUrl)) {
return;
}
goHomeActivity();
Intent intent = new Intent();
intent.setClass(this, BigimgActivity.class);
intent.putExtra(BigimgActivity.MEIZI_TITLE, "");
intent.putExtra(BigimgActivity.MEIZI_URL, mUrl);
startActivity(intent);
}
@Override
public void onBackPressed() {
// 禁掉返回键
}
@Override
protected void onDestroy() {
super.onDestroy();
mLauncherPresenter.unsubscribe();
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/launcher/LauncherContract.java
================================================
package me.bakumon.ugank.module.launcher;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
/**
* LauncherContract
* Created by bakumon on 17-3-21.
*/
public class LauncherContract {
interface View extends BaseView {
void goHomeActivity();
void loadImg(String url);
}
interface Presenter extends BasePresenter {
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/launcher/LauncherPresenter.java
================================================
package me.bakumon.ugank.module.launcher;
import android.text.TextUtils;
import me.bakumon.ugank.ConfigManage;
/**
* LauncherPresenter
* Created by bakumon on 17-3-21.
*/
public class LauncherPresenter implements LauncherContract.Presenter {
private LauncherContract.View mLauncherView;
public LauncherPresenter(LauncherContract.View view) {
mLauncherView = view;
}
@Override
public void subscribe() {
if (!ConfigManage.INSTANCE.isShowLauncherImg()) {
mLauncherView.goHomeActivity();
return;
}
String imgCacheUrl = ConfigManage.INSTANCE.getBannerURL();
if (!TextUtils.isEmpty(imgCacheUrl)) {
mLauncherView.loadImg(imgCacheUrl);
} else {
mLauncherView.goHomeActivity();
}
}
@Override
public void unsubscribe() {
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/search/HistoryListAdapter.java
================================================
package me.bakumon.ugank.module.search;
import android.content.Context;
import android.view.View;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.adapter.CommonAdapter4RecyclerView;
import me.bakumon.ugank.base.adapter.CommonHolder4RecyclerView;
import me.bakumon.ugank.base.adapter.ListenerWithPosition;
import me.bakumon.ugank.entity.History;
/**
* HistoryListAdapter
* Created by bakumon on 2017/2/18.
*/
public class HistoryListAdapter extends CommonAdapter4RecyclerView implements ListenerWithPosition.OnClickWithPositionListener {
public HistoryListAdapter(Context context) {
super(context, null, R.layout.item_history);
}
@Override
public void convert(CommonHolder4RecyclerView holder, History history) {
if (history != null) {
holder.setTextViewText(R.id.tv_item_content_history, history.getContent() == null ? "unknown" : history.getContent());
holder.setOnClickListener(this, R.id.tv_item_content_history);
}
}
@Override
public void onClick(View v, int position, CommonHolder4RecyclerView holder) {
if (mData.get(position) == null) {
return;
}
if (mOnItemClickListener != null) {
mOnItemClickListener.OnItemClick(mData.get(position));
}
}
private OnItemClickListener mOnItemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void OnItemClick(History history);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/search/SearchActivity.java
================================================
package me.bakumon.ugank.module.search;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.luolc.emojirain.EmojiRainLayout;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.SwipeBackBaseActivity;
import me.bakumon.ugank.entity.History;
import me.bakumon.ugank.entity.SearchResult;
import me.bakumon.ugank.utills.DisplayUtils;
import me.bakumon.ugank.utills.KeyboardUtils;
import me.bakumon.ugank.utills.MDTintUtil;
import me.bakumon.ugank.utills.StatusBarUtil;
import me.bakumon.ugank.widget.RecycleViewDivider;
import me.bakumon.ugank.widget.recyclerviewwithfooter.OnLoadMoreListener;
import me.bakumon.ugank.widget.recyclerviewwithfooter.RecyclerViewWithFooter;
public class SearchActivity extends SwipeBackBaseActivity implements SearchContract.View, TextWatcher, TextView.OnEditorActionListener, OnLoadMoreListener, HistoryListAdapter.OnItemClickListener {
@BindView(R.id.toolbar_search)
Toolbar mToolbarSearch;
@BindView(R.id.ed_search)
AppCompatEditText mEdSearch;
@BindView(R.id.iv_edit_clear)
AppCompatImageView mIvEditClear;
@BindView(R.id.iv_search)
AppCompatImageView mIvSearch;
@BindView(R.id.appbar_search)
AppBarLayout mAppbarSearch;
@BindView(R.id.recycler_view_search)
RecyclerViewWithFooter mRecyclerViewSearch;
@BindView(R.id.swipe_refresh_layout_search)
SwipeRefreshLayout mSwipeRefreshLayoutSearch;
@BindView(R.id.ll_search_history)
LinearLayout mLlHistory;
@BindView(R.id.recycler_search_history)
RecyclerView mRecyclerViewHistory;
@BindView(R.id.emoji_rainLayout)
EmojiRainLayout mEmojiRainLayout;
private SearchContract.Presenter mSearchPresenter = new SearchPresenter(this);
private SearchListAdapter mSearchListAdapter;
private HistoryListAdapter mHistoryListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_search);
ButterKnife.bind(this);
initView();
mSearchPresenter.subscribe();
mSearchPresenter.queryHistory();
}
private void initView() {
StatusBarUtil.immersive(this);
StatusBarUtil.setPaddingSmart(this, mToolbarSearch);
setSupportActionBar(mToolbarSearch);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
mToolbarSearch.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mEdSearch.addTextChangedListener(this);
mEdSearch.setOnEditorActionListener(this);
mSwipeRefreshLayoutSearch.setColorSchemeResources(
R.color.colorSwipeRefresh1,
R.color.colorSwipeRefresh2,
R.color.colorSwipeRefresh3,
R.color.colorSwipeRefresh4,
R.color.colorSwipeRefresh5,
R.color.colorSwipeRefresh6);
mSwipeRefreshLayoutSearch.setRefreshing(false);
mSwipeRefreshLayoutSearch.setEnabled(false);
mSearchListAdapter = new SearchListAdapter(this);
mRecyclerViewSearch.setLayoutManager(new LinearLayoutManager(this));
mRecyclerViewSearch.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL));
mRecyclerViewSearch.setAdapter(mSearchListAdapter);
mRecyclerViewSearch.setOnLoadMoreListener(this);
mRecyclerViewSearch.setEmpty();
mHistoryListAdapter = new HistoryListAdapter(this);
mHistoryListAdapter.setOnItemClickListener(this);
mHistoryListAdapter.mData = null;
mRecyclerViewHistory.setLayoutManager(new FlexboxLayoutManager());
mRecyclerViewHistory.setAdapter(mHistoryListAdapter);
mEmojiRainLayout.addEmoji(R.mipmap.emoji1);
mEmojiRainLayout.addEmoji(R.mipmap.emoji2);
mEmojiRainLayout.addEmoji(R.mipmap.emoji3);
mEmojiRainLayout.addEmoji(R.mipmap.emoji4);
mEmojiRainLayout.addEmoji(R.mipmap.emoji5);
mEmojiRainLayout.addEmoji(R.mipmap.emoji6);
}
@Override
protected void onDestroy() {
super.onDestroy();
mSearchPresenter.unsubscribe();
}
@Override
public void setToolbarBackgroundColor(int color) {
mAppbarSearch.setBackgroundColor(color);
}
@Override
public void setEditTextCursorColor(int cursorColor) {
MDTintUtil.setCursorTint(mEdSearch, cursorColor);
}
@Override
public void showEditClear() {
mIvEditClear.setVisibility(View.VISIBLE);
}
@Override
public void hideEditClear() {
mIvEditClear.setVisibility(View.GONE);
}
@Override
public void showSearchFail(String failMsg) {
Toasty.error(this, failMsg).show();
}
@Override
public void setSearchItems(SearchResult searchResult) {
mSearchListAdapter.mData = searchResult.results;
mSearchListAdapter.notifyDataSetChanged();
mSwipeRefreshLayoutSearch.setRefreshing(false);
}
@Override
public void addSearchItems(SearchResult searchResult) {
int start = mSearchListAdapter.getItemCount();
mSearchListAdapter.mData.addAll(searchResult.results);
mSearchListAdapter.notifyItemRangeInserted(start, searchResult.results.size());
}
@Override
public void showSwipLoading() {
mSwipeRefreshLayoutSearch.setRefreshing(true);
}
@Override
public void hideSwipLoading() {
mSwipeRefreshLayoutSearch.setRefreshing(false);
}
@Override
public void showTip(String msg) {
Toasty.warning(this, msg).show();
}
@Override
public void setLoadMoreIsLastPage() {
mRecyclerViewSearch.setEnd("没有更多数据了");
}
@Override
public void setEmpty() {
mRecyclerViewSearch.setEmpty();
}
@Override
public void setLoading() {
mRecyclerViewSearch.setLoading();
}
@Override
public void showSearchResult() {
mLlHistory.setVisibility(View.GONE);
mSwipeRefreshLayoutSearch.setVisibility(View.VISIBLE);
}
@Override
public void showSearchHistory() {
mLlHistory.setVisibility(View.VISIBLE);
mSwipeRefreshLayoutSearch.setVisibility(View.GONE);
}
@Override
public void setHistory(List history) {
mHistoryListAdapter.mData = history;
mHistoryListAdapter.notifyDataSetChanged();
}
@Override
public void startEmojiRain() {
mEmojiRainLayout.startDropping();
}
@Override
public void stopEmojiRain() {
mEmojiRainLayout.stopDropping();
}
@Override
public void onLoadMore() {
mSearchPresenter.search(mEdSearch.getText().toString().trim(), true);
}
@OnClick(R.id.iv_edit_clear)
public void editClear() {
mRecyclerViewSearch.setEmpty();
mEdSearch.setText("");
KeyboardUtils.showSoftInput(this, mEdSearch);
hideSwipLoading();
showSearchHistory();
mSearchPresenter.unsubscribe();
mSearchPresenter.queryHistory();
}
@OnClick(R.id.iv_search)
public void search() {
KeyboardUtils.hideSoftInput(this);
mSearchPresenter.search(mEdSearch.getText().toString().trim(), false);
}
@OnClick(R.id.tv_search_clean)
public void cleanHistory() {
mSearchPresenter.deleteAllHistory();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() > 0) {
showEditClear();
} else {
hideEditClear();
hideSwipLoading();
mSearchPresenter.unsubscribe();
mRecyclerViewSearch.setEmpty();
mSearchListAdapter.mData = null;
mSearchListAdapter.notifyDataSetChanged();
showSearchHistory();
mSearchPresenter.queryHistory();
}
}
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
search();
}
return false;
}
@Override
public void OnItemClick(History history) {
if (history == null || history.getContent() == null) {
return;
}
KeyboardUtils.hideSoftInput(this);
mEdSearch.setText(history.getContent());
mEdSearch.setSelection(mEdSearch.getText().toString().length());
mSearchPresenter.search(history.getContent(), false);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/search/SearchContract.java
================================================
package me.bakumon.ugank.module.search;
import java.util.List;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
import me.bakumon.ugank.entity.History;
import me.bakumon.ugank.entity.SearchResult;
/**
* SearchContract
* Created by bakumon on 2016/12/19 14:20.
*/
public interface SearchContract {
interface View extends BaseView {
void setToolbarBackgroundColor(int color);
void setEditTextCursorColor(int cursorColor);
void showEditClear();
void hideEditClear();
void showSearchFail(String failMsg);
void setSearchItems(SearchResult searchResult);
void addSearchItems(SearchResult searchResult);
void showSwipLoading();
void hideSwipLoading();
void showTip(String msg);
void setLoadMoreIsLastPage();
void setEmpty();
void setLoading();
void showSearchResult();
void showSearchHistory();
void setHistory(List history);
void startEmojiRain();
void stopEmojiRain();
}
interface Presenter extends BasePresenter {
void search(String searchText, boolean isLoadMore);
void queryHistory();
void deleteAllHistory();
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/search/SearchListAdapter.java
================================================
package me.bakumon.ugank.module.search;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.adapter.CommonAdapter4RecyclerView;
import me.bakumon.ugank.base.adapter.CommonHolder4RecyclerView;
import me.bakumon.ugank.base.adapter.ListenerWithPosition;
import me.bakumon.ugank.entity.Favorite;
import me.bakumon.ugank.entity.SearchResult;
import me.bakumon.ugank.module.bigimg.BigimgActivity;
import me.bakumon.ugank.module.webview.WebViewActivity;
import me.bakumon.ugank.utills.DateUtil;
/**
* SearchListAdapter
* Created by bakumon on 2016/12/20.
*/
public class SearchListAdapter extends CommonAdapter4RecyclerView implements ListenerWithPosition.OnClickWithPositionListener {
public SearchListAdapter(Context context) {
super(context, null, R.layout.item_search);
}
@Override
public void convert(CommonHolder4RecyclerView holder, SearchResult.ResultsBean searchResult) {
if (searchResult != null) {
holder.setTextViewText(R.id.tv_item_title_search, searchResult.desc == null ? "unknown" : searchResult.desc);
holder.setTextViewText(R.id.tv_item_type_search, searchResult.type == null ? "unknown" : searchResult.type);
holder.setTextViewText(R.id.tv_item_publisher_search, searchResult.who == null ? "unknown" : searchResult.who);
holder.setTextViewText(R.id.tv_item_time_search, DateUtil.dateFormat(searchResult.publishedAt));
holder.setOnClickListener(this, R.id.ll_item_search);
}
}
@Override
public void onClick(View v, int position, CommonHolder4RecyclerView holder) {
if (mData == null || mData.get(position) == null) {
Toasty.error(mContext, "数据异常").show();
return;
}
Intent intent = new Intent();
if ("福利".equals(mData.get(position).type)) {
intent.setClass(mContext, BigimgActivity.class);
intent.putExtra(BigimgActivity.MEIZI_TITLE, mData.get(position).desc);
intent.putExtra(BigimgActivity.MEIZI_URL, mData.get(position).url);
} else {
intent.setClass(mContext, WebViewActivity.class);
intent.putExtra(WebViewActivity.GANK_TITLE, mData.get(position).desc);
intent.putExtra(WebViewActivity.GANK_URL, mData.get(position).url);
Favorite favorite = new Favorite();
favorite.setAuthor(mData.get(position).who);
favorite.setData(mData.get(position).publishedAt);
favorite.setTitle(mData.get(position).desc);
favorite.setType(mData.get(position).type);
favorite.setUrl(mData.get(position).url);
favorite.setGankID(mData.get(position).ganhuo_id);
intent.putExtra(WebViewActivity.FAVORITE_DATA, favorite);
}
mContext.startActivity(intent);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/search/SearchPresenter.java
================================================
package me.bakumon.ugank.module.search;
import android.graphics.Color;
import android.text.TextUtils;
import org.litepal.crud.DataSupport;
import java.util.List;
import me.bakumon.ugank.GlobalConfig;
import me.bakumon.ugank.ThemeManage;
import me.bakumon.ugank.entity.History;
import me.bakumon.ugank.entity.SearchResult;
import me.bakumon.ugank.network.NetWork;
import me.bakumon.ugank.utills.EmojiFilter;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
/**
* SearchPresenter
* Created by bakumon on 2016/12/19 14:21.
*/
public class SearchPresenter implements SearchContract.Presenter {
private SearchContract.View mView;
private CompositeSubscription mSubscriptions;
private int mPage = 1;
public SearchPresenter(SearchContract.View view) {
mView = view;
}
@Override
public void subscribe() {
mSubscriptions = new CompositeSubscription();
mView.setToolbarBackgroundColor(ThemeManage.INSTANCE.getColorPrimary());
mView.setEditTextCursorColor(Color.WHITE);
mView.hideEditClear();
}
@Override
public void unsubscribe() {
mSubscriptions.clear();
}
@Override
public void search(final String searchText, final boolean isLoadMore) {
String searchTextNoEmoji = EmojiFilter.filterEmoji(searchText);
if (TextUtils.isEmpty(searchTextNoEmoji)) {
mView.startEmojiRain();
return;
}
if (TextUtils.isEmpty(searchText)) {
mView.showTip("搜索内容不能为空。");
return;
}
mView.showSearchResult();
saveOneHistory(searchText);
if (!isLoadMore) {
mView.showSwipLoading();
mPage = 1;
} else {
mPage += 1;
}
Subscription subscription = NetWork.getGankApi()
.getSearchResult(searchText, GlobalConfig.PAGE_SIZE_CATEGORY, mPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
mView.showSearchFail("搜索出错了。");
mView.hideSwipLoading();
}
@Override
public void onNext(SearchResult searchResult) {
if (!isLoadMore) {
if (searchResult == null || searchResult.count == 0) {
mView.showTip("没有搜索到结果");
mView.hideSwipLoading();
mView.showSearchHistory();
mView.setEmpty();
return;
}
mView.setSearchItems(searchResult);
mView.showSearchResult();
mView.setLoading();
} else {
mView.addSearchItems(searchResult);
mView.showSearchResult();
}
boolean isLastPage = searchResult.count < GlobalConfig.PAGE_SIZE_CATEGORY;
if (isLastPage) {
mView.setLoadMoreIsLastPage();
}
}
});
mSubscriptions.add(subscription);
}
@Override
public void queryHistory() {
// 展示查询所有,需要截取、去重和排序
List historyList = DataSupport.order("createTimeMill desc").limit(10).find(History.class);
// 将查询结果转为list对象
if (historyList == null || historyList.size() < 1) {
mView.showSearchResult();
} else {
mView.setHistory(historyList);
}
}
private void saveOneHistory(String historyContent) {
if (TextUtils.isEmpty(historyContent)) {
return;
}
// 不知道 LitePal 支不支持去重
// 先这样写吧,新增之前查询是否有相同数据,有就更新 CreateTimeMill ,没有就直接新增
List historyList = DataSupport.where("content = ?", historyContent).find(History.class);
if (historyList == null || historyList.size() < 1) { // 不存在
History history = new History();
history.setCreateTimeMill(System.currentTimeMillis());
history.setContent(historyContent);
history.save();
} else {
// 更新
History updateNews = new History();
updateNews.setCreateTimeMill(System.currentTimeMillis());
updateNews.updateAll("content = ?", historyContent);
}
}
@Override
public void deleteAllHistory() {
DataSupport.deleteAll(History.class);
mView.showSearchResult();
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/setting/SettingActivity.java
================================================
package me.bakumon.ugank.module.setting;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.SwipeBackBaseActivity;
import me.bakumon.ugank.utills.AlipayZeroSdk;
import me.bakumon.ugank.utills.DisplayUtils;
import me.bakumon.ugank.utills.MDTintUtil;
import me.bakumon.ugank.utills.StatusBarUtil;
import me.bakumon.ugank.widget.AboutDialog;
public class SettingActivity extends SwipeBackBaseActivity implements SettingContract.View, CompoundButton.OnCheckedChangeListener {
@BindView(R.id.toolbar_setting)
Toolbar mToolbarSetting;
@BindView(R.id.switch_setting)
SwitchCompat mSwitchSetting;
@BindView(R.id.appbar_setting)
AppBarLayout mAppbarSetting;
@BindView(R.id.tv_setting_version_name)
AppCompatTextView mTvSettingVersionName;
@BindView(R.id.ll_setting_image_quality)
LinearLayout mLlImageQuality;
@BindView(R.id.tv_setting_image_quality_title)
TextView mTvImageQualityTitle;
@BindView(R.id.tv_setting_image_quality_content)
TextView mTvImageQualityContent;
@BindView(R.id.tv_setting_image_quality_tip)
TextView mTvImageQualityTip;
@BindView(R.id.tv_setting_clean_cache)
TextView mTvCleanCache;
@BindView(R.id.switch_setting_show_launcher_img)
SwitchCompat mSwitchSettingShowLauncherImg;
@BindView(R.id.switch_setting_always_show_launcher_img)
SwitchCompat mSwitchSettingAlwaysShowLauncherImg;
@BindView(R.id.ll_is_always_show_launcher_img)
LinearLayout mLlAlwaysShowLauncherImg;
@BindView(R.id.tv_is_always_show_launcher_img_title)
AppCompatTextView mTvAlwaysShowLauncherImgTitle;
@BindView(R.id.tv_is_always_show_launcher_img_content)
AppCompatTextView mTvAlwaysShowLauncherImgContent;
@BindView(R.id.tv_is_show_launcher_img_content)
AppCompatTextView mTvShowLauncherImgContent;
private SettingPresenter mSettingPresenter = new SettingPresenter(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_setting);
ButterKnife.bind(this);
StatusBarUtil.immersive(this);
StatusBarUtil.setPaddingSmart(this, mAppbarSetting);
setSupportActionBar(mToolbarSetting);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
mToolbarSetting.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
mSwitchSetting.setOnCheckedChangeListener(this);
mSwitchSettingShowLauncherImg.setOnCheckedChangeListener(this);
mSwitchSettingAlwaysShowLauncherImg.setOnCheckedChangeListener(this);
mSettingPresenter.subscribe();
}
@Override
public void onBackPressed() {
if (mSettingPresenter.isThumbnailSettingChanged()) { // 显示缩略图设置项改变
setResult(RESULT_OK);
}
super.onBackPressed();
}
@Override
protected void onDestroy() {
super.onDestroy();
mSettingPresenter.unsubscribe();
}
@OnClick(R.id.ll_is_show_list_img)
public void changSwitchState(View view) {
mSwitchSetting.setChecked(!mSwitchSetting.isChecked());
}
@OnClick(R.id.ll_is_show_launcher_img)
public void isShowLauncherImg() {
mSwitchSettingShowLauncherImg.setChecked(!mSwitchSettingShowLauncherImg.isChecked());
}
@OnClick(R.id.ll_is_always_show_launcher_img)
public void isAlwaysShowLauncherImg() {
mSwitchSettingAlwaysShowLauncherImg.setChecked(!mSwitchSettingAlwaysShowLauncherImg.isChecked());
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
switch (compoundButton.getId()) {
case R.id.switch_setting:
mSettingPresenter.saveIsListShowImg(isChecked);
break;
case R.id.switch_setting_show_launcher_img:
mSettingPresenter.saveIsLauncherShowImg(isChecked);
break;
case R.id.switch_setting_always_show_launcher_img:
mSettingPresenter.saveIsLauncherAlwaysShowImg(isChecked);
break;
}
}
@Override
public void setToolbarBackgroundColor(int color) {
mAppbarSetting.setBackgroundColor(color);
}
@Override
public void changeSwitchState(boolean isChecked) {
mSwitchSetting.setChecked(isChecked);
}
@Override
public void changeIsShowLauncherImgSwitchState(boolean isChecked) {
mSwitchSettingShowLauncherImg.setChecked(isChecked);
}
@Override
public void changeIsAlwaysShowLauncherImgSwitchState(boolean isChecked) {
mSwitchSettingAlwaysShowLauncherImg.setChecked(isChecked);
}
@Override
public void setSwitchCompatsColor(int color) {
MDTintUtil.setTint(mSwitchSetting, color);
MDTintUtil.setTint(mSwitchSettingShowLauncherImg, color);
MDTintUtil.setTint(mSwitchSettingAlwaysShowLauncherImg, color);
}
@Override
public void setAppVersionNameInTv(String versionName) {
mTvSettingVersionName.setText("版本: " + versionName);
}
@Override
public void setImageQualityChooseUnEnable() {
mLlImageQuality.setClickable(false);
mTvImageQualityTitle.setTextColor(getResources().getColor(R.color.colorTextUnEnable));
mTvImageQualityContent.setTextColor(getResources().getColor(R.color.colorTextUnEnable));
mTvImageQualityTip.setTextColor(getResources().getColor(R.color.colorTextUnEnable));
}
@Override
public void setImageQualityChooseEnable() {
mLlImageQuality.setClickable(true);
mTvImageQualityTitle.setTextColor(getResources().getColor(R.color.colorTextEnable));
mTvImageQualityContent.setTextColor(getResources().getColor(R.color.colorTextEnableGary));
mTvImageQualityTip.setTextColor(getResources().getColor(R.color.colorTextEnableGary));
}
@Override
public void setLauncherImgProbabilityUnEnable() {
mLlAlwaysShowLauncherImg.setClickable(false);
mSwitchSettingAlwaysShowLauncherImg.setClickable(false);
mTvAlwaysShowLauncherImgTitle.setTextColor(getResources().getColor(R.color.colorTextUnEnable));
mTvAlwaysShowLauncherImgContent.setTextColor(getResources().getColor(R.color.colorTextUnEnable));
}
@Override
public void setLauncherImgProbabilityEnable() {
mLlAlwaysShowLauncherImg.setClickable(true);
mSwitchSettingAlwaysShowLauncherImg.setClickable(true);
mTvAlwaysShowLauncherImgTitle.setTextColor(getResources().getColor(R.color.colorTextEnable));
mTvAlwaysShowLauncherImgContent.setTextColor(getResources().getColor(R.color.colorTextEnableGary));
}
@Override
public void setThumbnailQualityInfo(int quality) {
String thumbnailQuality = "";
switch (quality) {
case 0:
thumbnailQuality = "原图";
break;
case 1:
thumbnailQuality = "默认";
break;
case 2:
thumbnailQuality = "省流";
break;
}
mTvImageQualityContent.setText(thumbnailQuality);
}
@Override
public void showCacheSize(String cache) {
mTvCleanCache.setText(cache);
}
@Override
public void showSuccessTip(String msg) {
Toasty.success(this, msg).show();
}
@Override
public void showFailTip(String msg) {
Toasty.error(this, msg).show();
}
@Override
public void setShowLauncherTip(String tip) {
mTvShowLauncherImgContent.setText(tip);
}
@Override
public void setAlwaysShowLauncherTip(String tip) {
mTvAlwaysShowLauncherImgContent.setText(tip);
}
@OnClick(R.id.ll_setting_image_quality)
public void chooseThumbnailQuality() {
new MaterialDialog.Builder(this)
.title("缩略图质量")
.items("原图", "默认", "省流")
.widgetColor(mSettingPresenter.getColorPrimary())
.alwaysCallSingleChoiceCallback()
.itemsCallbackSingleChoice(mSettingPresenter.getThumbnailQuality(), new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
mSettingPresenter.setThumbnailQuality(which);
dialog.dismiss();
return true;
}
})
.positiveText("取消")
.positiveColor(mSettingPresenter.getColorPrimary())
.show();
}
@OnClick(R.id.ll_setting_about)
public void about() {
new AboutDialog(this, mSettingPresenter.getColorPrimary()).show();
}
@OnClick(R.id.ll_setting_clean_cache)
public void cleanCache() {
mSettingPresenter.cleanCache();
}
@OnClick(R.id.ll_setting_issues)
public void issues() {
Uri uri = Uri.parse("https://github.com/Bakumon/UGank/issues");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
@OnClick(R.id.ll_setting_pay)
public void pay() {
// https://fama.alipay.com/qrcode/qrcodelist.htm?qrCodeType=P 二维码地址
// http://cli.im/deqr/ 解析二维码
// aex01251c8foqaprudcp503
if (AlipayZeroSdk.hasInstalledAlipayClient(this)) {
AlipayZeroSdk.startAlipayClient(this, "aex01251c8foqaprudcp503");
} else {
Toasty.info(this, "谢谢,您没有安装支付宝客户端").show();
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/setting/SettingContract.java
================================================
package me.bakumon.ugank.module.setting;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
/**
* SettingContract
* Created by bakumon on 2016/12/15 17:05.
*/
public interface SettingContract {
interface View extends BaseView {
void setToolbarBackgroundColor(int color);
void changeSwitchState(boolean isChecked);
void changeIsShowLauncherImgSwitchState(boolean isChecked);
void changeIsAlwaysShowLauncherImgSwitchState(boolean isChecked);
void setSwitchCompatsColor(int color);
void setAppVersionNameInTv(String versionName);
void setImageQualityChooseUnEnable();
void setImageQualityChooseEnable();
void setLauncherImgProbabilityUnEnable();
void setLauncherImgProbabilityEnable();
void setThumbnailQualityInfo(int quality);
void showCacheSize(String cache);
void showSuccessTip(String msg);
void showFailTip(String msg);
void setShowLauncherTip(String tip);
void setAlwaysShowLauncherTip(String tip);
}
interface Presenter extends BasePresenter {
boolean isThumbnailSettingChanged();
void saveIsListShowImg(boolean isListShowImg);
void saveIsLauncherShowImg(boolean isLauncherShowImg);
void saveIsLauncherAlwaysShowImg(boolean isLauncherAlwaysShowImg);
int getColorPrimary();
int getThumbnailQuality();
void setThumbnailQuality(int quality);
void cleanCache();
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/setting/SettingPresenter.java
================================================
package me.bakumon.ugank.module.setting;
import me.bakumon.ugank.App;
import me.bakumon.ugank.ConfigManage;
import me.bakumon.ugank.ThemeManage;
import me.bakumon.ugank.utills.DataCleanManager;
import me.bakumon.ugank.utills.PackageUtil;
import rx.subscriptions.CompositeSubscription;
/**
* SettingPresenter
* Created by bakumon on 2016/12/15 17:08.
*/
public class SettingPresenter implements SettingContract.Presenter {
private SettingContract.View mView;
private CompositeSubscription mSubscriptions;
private boolean mSwitchSettingInitState;
private int mTvImageQualityContentInitState;
public SettingPresenter(SettingContract.View view) {
mView = view;
}
@Override
public void subscribe() {
mSubscriptions = new CompositeSubscription();
// 设置 View 界面的主题色
mView.setSwitchCompatsColor(ThemeManage.INSTANCE.getColorPrimary());
mView.setToolbarBackgroundColor(ThemeManage.INSTANCE.getColorPrimary());
// 初始化开关显示状态
mView.changeSwitchState(ConfigManage.INSTANCE.isListShowImg());
mView.changeIsShowLauncherImgSwitchState(ConfigManage.INSTANCE.isShowLauncherImg());
mView.changeIsAlwaysShowLauncherImgSwitchState(ConfigManage.INSTANCE.isProbabilityShowLauncherImg());
setImageQualityChooseIsEnable(ConfigManage.INSTANCE.isListShowImg());
setIsLauncherAlwaysShowImgEnable(ConfigManage.INSTANCE.isShowLauncherImg());
mView.setAppVersionNameInTv(PackageUtil.getVersionName(App.getInstance()));
setThumbnailQuality(ConfigManage.INSTANCE.getThumbnailQuality());
mView.showCacheSize(DataCleanManager.getTotalCacheSize());
mSwitchSettingInitState = ConfigManage.INSTANCE.isListShowImg();
mTvImageQualityContentInitState = ConfigManage.INSTANCE.getThumbnailQuality();
}
@Override
public boolean isThumbnailSettingChanged() {
return mSwitchSettingInitState != ConfigManage.INSTANCE.isListShowImg()
|| mTvImageQualityContentInitState > ConfigManage.INSTANCE.getThumbnailQuality();
}
@Override
public void unsubscribe() {
mSubscriptions.clear();
}
@Override
public void saveIsListShowImg(boolean isListShowImg) {
ConfigManage.INSTANCE.setListShowImg(isListShowImg);
setImageQualityChooseIsEnable(isListShowImg);
}
@Override
public void saveIsLauncherShowImg(boolean isLauncherShowImg) {
ConfigManage.INSTANCE.setShowLauncherImg(isLauncherShowImg);
setIsLauncherAlwaysShowImgEnable(isLauncherShowImg);
if (isLauncherShowImg) {
mView.setShowLauncherTip("没有妹子太寂寞");
} else {
mView.setShowLauncherTip("基佬怎么会需要妹子");
}
}
@Override
public void saveIsLauncherAlwaysShowImg(boolean isLauncherAlwaysShowImg) {
ConfigManage.INSTANCE.setProbabilityShowLauncherImg(isLauncherAlwaysShowImg);
if (isLauncherAlwaysShowImg) {
mView.setAlwaysShowLauncherTip("偶尔来个惊喜就行");
} else {
mView.setAlwaysShowLauncherTip("我每次都要幸临,没毛病");
}
}
private void setIsLauncherAlwaysShowImgEnable(boolean isEnable) {
if (isEnable) {
mView.setLauncherImgProbabilityEnable();
} else {
mView.setLauncherImgProbabilityUnEnable();
}
}
private void setImageQualityChooseIsEnable(boolean isEnable) {
if (isEnable) {
mView.setImageQualityChooseEnable();
} else {
mView.setImageQualityChooseUnEnable();
}
}
@Override
public int getColorPrimary() {
return ThemeManage.INSTANCE.getColorPrimary();
}
@Override
public int getThumbnailQuality() {
return ConfigManage.INSTANCE.getThumbnailQuality();
}
@Override
public void setThumbnailQuality(int quality) {
ConfigManage.INSTANCE.setThumbnailQuality(quality);
mView.setThumbnailQualityInfo(quality);
}
@Override
public void cleanCache() {
if (DataCleanManager.clearAllCache()) {
ConfigManage.INSTANCE.setBannerURL("");
mView.showSuccessTip("缓存清理成功!");
} else {
mView.showFailTip("缓存清理失败!");
}
try {
mView.showCacheSize(DataCleanManager.getTotalCacheSize());
} catch (Exception e) {
e.printStackTrace();
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/webview/WebViewActivity.java
================================================
package me.bakumon.ugank.module.webview;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.SwipeBackBaseActivity;
import me.bakumon.ugank.entity.Favorite;
import me.bakumon.ugank.module.favorite.FavoriteActivity;
import me.bakumon.ugank.utills.AndroidUtil;
import me.bakumon.ugank.utills.MDTintUtil;
import me.bakumon.ugank.utills.StatusBarUtil;
import me.bakumon.ugank.widget.ObservableWebView;
public class WebViewActivity extends SwipeBackBaseActivity implements WebViewContract.View {
public static final String GANK_URL = "me.bakumon.gank.module.webview.WebViewActivity.gank_url";
public static final String GANK_TITLE = "me.bakumon.gank.module.webview.WebViewActivity.gank_title";
public static final String FAVORITE_DATA = "me.bakumon.gank.module.webview.WebViewActivity.favorite_data";
public static final String FAVORITE_POSITION = "me.bakumon.gank.module.webview.WebViewActivity.favorite_position";
@BindView(R.id.toolbar)
Toolbar mToolbar;
@BindView(R.id.tv_title)
TextView mTvTitle;
@BindView(R.id.web_view)
ObservableWebView mWebView;
@BindView(R.id.progressbar_webview)
ProgressBar mProgressbar;
@BindView(R.id.appbar)
AppBarLayout mAppbar;
@BindView(R.id.fab_web_favorite)
FloatingActionButton mFloatingActionButton;
private WebViewContract.Presenter mWebViewPresenter = new WebViewPresenter(this);
private boolean isForResult; // 是否回传结果
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_web_view);
ButterKnife.bind(this);
StatusBarUtil.immersive(this);
StatusBarUtil.setPaddingSmart(this, mToolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
initWebView();
mWebViewPresenter.subscribe();
}
public void initWebView() {
WebSettings settings = mWebView.getSettings();
settings.setLoadWithOverviewMode(true);
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setSupportZoom(true);
mWebView.setWebChromeClient(new MyWebChrome());
mWebView.setWebViewClient(new MyWebClient());
mWebView.setOnScrollChangedCallback(new ObservableWebView.OnScrollChangedCallback() {
@Override
public void onScroll(int dx, int dy) {
if (dy > 0) {
mFloatingActionButton.hide();
} else {
mFloatingActionButton.show();
}
}
});
}
@Override
public void setToolbarBackgroundColor(int color) {
mAppbar.setBackgroundColor(color);
}
@Override
public String getLoadUrl() {
return getIntent().getStringExtra(WebViewActivity.GANK_URL);
}
@Override
public String getGankTitle() {
return getIntent().getStringExtra(WebViewActivity.GANK_TITLE);
}
@Override
public Favorite getFavoriteData() {
return (Favorite) getIntent().getSerializableExtra(WebViewActivity.FAVORITE_DATA);
}
@Override
public void setFavoriteState(boolean isFavorite) {
if (isFavorite) {
mFloatingActionButton.setImageResource(R.drawable.ic_favorite);
} else {
mFloatingActionButton.setImageResource(R.drawable.ic_unfavorite);
}
isForResult = !isFavorite;
}
@Override
public void finish() {
if (isForResult) {
Intent intent = new Intent();
intent.putExtra(FavoriteActivity.FAVORITE_POSITION, getIntent().getIntExtra(WebViewActivity.FAVORITE_POSITION, -1));
setResult(RESULT_OK, intent);
}
super.finish();
}
@Override
public void hideFavoriteFab() {
mFloatingActionButton.setVisibility(View.GONE);
mWebView.setOnScrollChangedCallback(null);
}
@Override
public void showTip(String tip) {
Toasty.error(this, tip).show();
}
@Override
public void setFabButtonColor(int color) {
MDTintUtil.setTint(mFloatingActionButton, color);
}
private class MyWebChrome extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
mProgressbar.setVisibility(View.VISIBLE);
mProgressbar.setProgress(newProgress);
}
}
private class MyWebClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
mProgressbar.setVisibility(View.GONE);
}
}
@Override
public void setGankTitle(String title) {
mTvTitle.setText(title);
}
@Override
public void loadGankURL(String url) {
mWebView.loadUrl(url);
}
@OnClick(R.id.fab_web_favorite)
public void favorite() {
mWebViewPresenter.favoriteGank();
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_webview, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
AndroidUtil.share(this, mWebViewPresenter.getGankUrl());
break;
case R.id.menu_copy_link:
if (AndroidUtil.copyText(this, mWebViewPresenter.getGankUrl())) {
Toasty.success(this, "链接复制成功").show();
}
break;
case R.id.menu_open_with:
AndroidUtil.openWithBrowser(this, mWebViewPresenter.getGankUrl());
break;
}
return super.onOptionsItemSelected(item);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/webview/WebViewContract.java
================================================
package me.bakumon.ugank.module.webview;
import me.bakumon.ugank.base.BasePresenter;
import me.bakumon.ugank.base.BaseView;
import me.bakumon.ugank.entity.Favorite;
/**
* WebViewContract
* Created by bakumon on 16-12-10.
*/
public interface WebViewContract {
interface View extends BaseView {
void setGankTitle(String title);
void loadGankURL(String url);
void setToolbarBackgroundColor(int color);
String getLoadUrl();
String getGankTitle();
void setFabButtonColor(int color);
Favorite getFavoriteData();
void setFavoriteState(boolean isFavorite);
void hideFavoriteFab();
void showTip(String tip);
}
interface Presenter extends BasePresenter {
String getGankUrl();
void favoriteGank();
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/module/webview/WebViewPresenter.java
================================================
package me.bakumon.ugank.module.webview;
import org.litepal.crud.DataSupport;
import java.util.List;
import me.bakumon.ugank.ThemeManage;
import me.bakumon.ugank.entity.Favorite;
/**
* WebViewPresenter
* Created by bakumon on 16-12-10.
*/
public class WebViewPresenter implements WebViewContract.Presenter {
private WebViewContract.View mWebViewView;
private String mGankUrl;
private boolean mIsFavorite;
private Favorite mFavoriteData;
public WebViewPresenter(WebViewContract.View webViewView) {
mWebViewView = webViewView;
}
@Override
public void subscribe() {
mWebViewView.setToolbarBackgroundColor(ThemeManage.INSTANCE.getColorPrimary());
mWebViewView.setGankTitle(mWebViewView.getGankTitle());
// 设置 FabButton 的背景色
mWebViewView.setFabButtonColor(ThemeManage.INSTANCE.getColorPrimary());
mFavoriteData = mWebViewView.getFavoriteData();
findHasFavoriteGank();
loadDate();
}
private void loadDate() {
mGankUrl = mWebViewView.getLoadUrl();
mWebViewView.loadGankURL(mGankUrl);
}
@Override
public void unsubscribe() {
}
@Override
public String getGankUrl() {
return mGankUrl;
}
@Override
public void favoriteGank() {
if (mIsFavorite) { // 已经收藏
unFavorite();
} else { // 未收藏
favorite();
}
}
private void unFavorite() {
int cows = DataSupport.deleteAll(Favorite.class, "gankID = ?", mFavoriteData.getGankID());
// 不调用这句保存 在保存会失败,并且返回的是true
// https://github.com/LitePalFramework/LitePal/issues/77
mFavoriteData.clearSavedState();
mIsFavorite = cows < 1;
mWebViewView.setFavoriteState(mIsFavorite);
if (mIsFavorite) {
mWebViewView.showTip("取消收藏失败,请重试");
}
}
private void favorite() {
mFavoriteData.setCreatetime(System.currentTimeMillis());
mIsFavorite = mFavoriteData.save();
mWebViewView.setFavoriteState(mIsFavorite);
if (!mIsFavorite) {
mWebViewView.showTip("收藏失败,请重试");
}
}
private void findHasFavoriteGank() {
if (mFavoriteData == null) {
// 隐藏收藏 fab
mWebViewView.hideFavoriteFab();
return;
}
List favorites = DataSupport.where("gankID = ?", mFavoriteData.getGankID()).find(Favorite.class);
mIsFavorite = favorites.size() > 0;
mWebViewView.setFavoriteState(mIsFavorite);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/network/NetWork.java
================================================
package me.bakumon.ugank.network;
import me.bakumon.ugank.network.api.GankApi;
import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* 网络层
* Created by bakumon on 16-12-1.
*/
public class NetWork {
private static GankApi gankApi;
private static OkHttpClient okHttpClient = new OkHttpClient();
private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
public static GankApi getGankApi() {
if (gankApi == null) {
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl("http://gank.io/api/")
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
gankApi = retrofit.create(GankApi.class);
}
return gankApi;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/network/api/GankApi.java
================================================
package me.bakumon.ugank.network.api;
import me.bakumon.ugank.entity.CategoryResult;
import me.bakumon.ugank.entity.SearchResult;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
/**
* gank.io 接口
* Created by bakumon on 16-12-1.
*/
public interface GankApi {
@GET("data/{category}/{number}/{page}")
Observable getCategoryDate(@Path("category") String category, @Path("number") int number, @Path("page") int page);
@GET("random/data/福利/{number}")
Observable getRandomBeauties(@Path("number") int number);
@GET("search/query/{key}/category/all/count/{count}/page/{page}")
Observable getSearchResult(@Path("key") String key, @Path("count") int count, @Path("page") int page);
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/AlipayZeroSdk.java
================================================
package me.bakumon.ugank.utills;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.service.quicksettings.TileService;
import java.net.URISyntaxException;
public class AlipayZeroSdk {
// 支付宝包名
private static final String ALIPAY_PACKAGE_NAME = "com.eg.android.AlipayGphone";
// 旧版支付宝二维码通用 Intent Scheme Url 格式
private static final String INTENT_URL_FORMAT = "intent://platformapi/startapp?saId=10000007&" +
"clientVersion=3.7.0.0718&qrcode=https%3A%2F%2Fqr.alipay.com%2F{urlCode}%3F_s" +
"%3Dweb-other&_t=1472443966571#Intent;" +
"scheme=alipayqr;package=com.eg.android.AlipayGphone;end";
/**
* 打开转账窗口
* 旧版支付宝二维码方法,需要使用 https://fama.alipay.com/qrcode/index.htm 网站生成的二维码
* 这个方法最好,但在 2016 年 8 月发现新用户可能无法使用
*
* @param activity Parent Activity
* @param urlCode 手动解析二维码获得地址中的参数,例如 https://qr.alipay.com/aehvyvf4taua18zo6e 最后那段
* @return 是否成功调用
*/
public static boolean startAlipayClient(Activity activity, String urlCode) {
return startIntentUrl(activity, INTENT_URL_FORMAT.replace("{urlCode}", urlCode));
}
/**
* 打开 Intent Scheme Url
*
* @param activity Parent Activity
* @param intentFullUrl Intent 跳转地址
* @return 是否成功调用
*/
public static boolean startIntentUrl(Activity activity, String intentFullUrl) {
try {
Intent intent = Intent.parseUri(
intentFullUrl,
Intent.URI_INTENT_SCHEME
);
activity.startActivity(intent);
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
return false;
} catch (ActivityNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 判断支付宝客户端是否已安装,建议调用转账前检查
* @param context Context
* @return 支付宝客户端是否已安装
*/
public static boolean hasInstalledAlipayClient(Context context) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo info = pm.getPackageInfo(ALIPAY_PACKAGE_NAME, 0);
return info != null;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 获取支付宝客户端版本名称,作用不大
* @param context Context
* @return 版本名称
*/
public static String getAlipayClientVersion(Context context) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo info = pm.getPackageInfo(ALIPAY_PACKAGE_NAME, 0);
return info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 打开支付宝扫一扫界面
* @param context Context
* @return 是否成功打开 Activity
*/
public static boolean openAlipayScan(Context context) {
try {
Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
if (context instanceof TileService) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
((TileService) context).startActivityAndCollapse(intent);
}
} else {
context.startActivity(intent);
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* 打开支付宝付款码
* @param context Context
* @return 是否成功打开 Activity
*/
public static boolean openAlipayBarcode(Context context) {
try {
Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=20000056");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
if (context instanceof TileService) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
((TileService) context).startActivityAndCollapse(intent);
}
} else {
context.startActivity(intent);
}
return true;
} catch (Exception e) {
return false;
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/AndroidUtil.java
================================================
package me.bakumon.ugank.utills;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
/**
* AndroidUtil
* Created by bakumon on 2016/12/12 11:00.
*/
public class AndroidUtil {
/**
* 使用系统发送分享数据
*
* @param context 上下文
* @param text 要分享的文本
*/
public static void share(Context context, String text) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent, "分享到"));
}
/**
* 使用浏览器打开
*
* @param context 上下文
* @param uriStr 链接地址
*/
public static void openWithBrowser(Context context, String uriStr) {
Uri uri = Uri.parse(uriStr);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
/**
* 复制文字到剪切板
* @param context 上下文
* @param copyText 要复制的文本
*/
public static boolean copyText(Context context, String copyText) {
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData data = ClipData.newRawUri("gankUrl", Uri.parse(copyText));
cmb.setPrimaryClip(data);
return true;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/DataCleanManager.java
================================================
package me.bakumon.ugank.utills;
import android.os.Environment;
import java.io.File;
import java.math.BigDecimal;
import me.bakumon.ugank.App;
/**
* 清理缓存
* Created by bakumon on 17-3-6.
*/
public class DataCleanManager {
public static String getTotalCacheSize() {
long cacheSize;
try {
cacheSize = getFolderSize(App.getInstance().getCacheDir());
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cacheSize += getFolderSize(App.getInstance().getExternalCacheDir());
}
} catch (Exception e) {
cacheSize = 0;
}
return getFormatSize(cacheSize);
}
// 获取文件
//Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录,一般放一些长时间保存的数据
//Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
public static long getFolderSize(File file) throws Exception {
long size = 0;
try {
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
// 如果下面还有文件
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
public static boolean clearAllCache() {
if (!deleteDir(App.getInstance().getCacheDir())) {
return false;
}
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (!deleteDir(App.getInstance().getExternalCacheDir())) {
return false;
}
}
return true;
}
private static boolean deleteDir(File dir) {
if (dir == null) {
return false;
}
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
/**
* 格式化单位
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
// return size + "Byte";
return "0K";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
+ "TB";
}
/**
* 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * * @param context
*/
public static void cleanInternalCache() {
deleteFilesByDirectory(App.getInstance().getCacheDir());
}
/**
* 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * @param context
*/
public static void cleanDatabases() {
deleteFilesByDirectory(new File("/data/data/"
+ App.getInstance().getPackageName() + "/databases"));
}
/**
* * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param
* context
*/
public static void cleanSharedPreference() {
deleteFilesByDirectory(new File("/data/data/"
+ App.getInstance().getPackageName() + "/shared_prefs"));
}
/**
* 按名字清除本应用数据库 * * @param context * @param dbName
*/
public static void cleanDatabaseByName(String dbName) {
App.getInstance().deleteDatabase(dbName);
}
/**
* 清除/data/data/com.xxx.xxx/files下的内容 * * @param context
*/
public static void cleanFiles() {
deleteFilesByDirectory(App.getInstance().getFilesDir());
}
/**
* * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param
* context
*/
public static void cleanExternalCache() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(App.getInstance().getExternalCacheDir());
}
}
/**
* 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * * @param filePath
*/
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/**
* 清除本应用所有的数据 * * @param context * @param filepath
*/
public static void cleanApplicationData(String... filepath) {
cleanInternalCache();
cleanExternalCache();
cleanDatabases();
cleanSharedPreference();
cleanFiles();
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/**
* 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * * @param directory
*/
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/DateUtil.java
================================================
package me.bakumon.ugank.utills;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期工具类
* Created by bakumon on 2016/12/8 17:18.
*/
public class DateUtil {
public static String dateFormat(String timestamp) {
if (timestamp == null) {
return "unknown";
}
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = inputFormat.parse(timestamp);
return outputFormat.format(date);
} catch (ParseException e) {
return "unknown";
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/DisplayUtils.java
================================================
package me.bakumon.ugank.utills;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;
/**
* DisplayUtils
* Created by bakumon on 2016/12/14.
*/
public class DisplayUtils {
private static DisplayMetrics getMetrics(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
return metrics;
}
/**
* dp 转 px
*/
public static int dp2px(float dp, Context context) {
DisplayMetrics metrics = getMetrics(context);
return (int) (dp * (metrics.densityDpi / 160f));
}
/**
* pxe 转 dp
*/
public static float px2dp(float px, Context context) {
DisplayMetrics metrics = getMetrics(context);
return px / (metrics.densityDpi / 160f);
}
/**
* 获取屏幕宽度 px
*/
public static int getScreenWidth(Context context) {
DisplayMetrics dm = getMetrics(context);
return dm.widthPixels;
}
/**
* 获取屏幕高度 px
*/
public static int getScreenHeight(Context context) {
DisplayMetrics dm = getMetrics(context);
return dm.heightPixels;
}
/**
* 获取状态栏高度
*/
public static int getStatusBarHeight(Context context) {
int result = 38;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/EmojiFilter.java
================================================
package me.bakumon.ugank.utills;
/**
* Created by mafei on 2017/3/24 12:27.
*
* @author mafei
* @version 1.0.0
* @class EmojiFilter
* @describe
*/
public class EmojiFilter {
/**
* 是否包含表情
*
* @param codePoint
* @return 如果不包含 返回false,包含 则返回true
* @author 杨振威 2015-3-26 下午2:41:08
*/
private static boolean isEmojiCharacter(char codePoint) {
return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
|| (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
}
/**
* 过滤emoji 或者 其他非文字类型的字符
*
* @param source
* @return
* @author 杨振威 2015-3-26 下午2:42:11
*/
public static String filterEmoji(String source) {
StringBuilder buf = null;
int len = source.length();
for (int i = 0; i < len; i++) {
char codePoint = source.charAt(i);
if (!isEmojiCharacter(codePoint)) {// 如果不包含 则将字符append
if (buf == null) {
buf = new StringBuilder(source.length());
}
buf.append(codePoint);
} else {
}
}
if (buf == null) {
return "";// 如果没有找到 emoji表情,则返回源字符串
} else {
if (buf.length() == len) {// 这里的意义在于尽可能少的toString,因为会重新生成字符串
buf = null;
return source;
} else {
return buf.toString();
}
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/ImageUtil.java
================================================
package me.bakumon.ugank.utills;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* ImageUtil
* Created by bakumon on 2016/12/26 15:59.
*/
public class ImageUtil {
public static boolean saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = Environment.getExternalStorageDirectory();
if (!appDir.exists()) {
if (!appDir.mkdir()) {
return false;
}
}
String fileName = System.currentTimeMillis() + ".JPEG";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
// 其次把文件插入到系统图库
String insertImageUri;
try {
insertImageUri = MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
// 删除保存的图片(非图库中)
File fileDel = new File(appDir, fileName);
fileDel.delete();
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(insertImageUri)));
return true;
}
public static Bitmap drawableToBitmap(Drawable drawable) {
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/KeyboardUtils.java
================================================
package me.bakumon.ugank.utills;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* KeyboardUtils
* Created by bakumon on 2016/12/20 18:28.
*/
public class KeyboardUtils {
/**
* 动态隐藏软键盘
*
* @param activity activity
*/
public static void hideSoftInput(Activity activity) {
View view = activity.getCurrentFocus();
if (view == null) view = new View(activity);
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* 动态显示软键盘
*
* @param edit 输入框
*/
public static void showSoftInput(Context context, EditText edit) {
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/MDTintUtil.java
================================================
package me.bakumon.ugank.utills;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.SwitchCompat;
import android.widget.EditText;
import android.widget.TextView;
import java.lang.reflect.Field;
/**
* MD 风格的控件着色
*/
public class MDTintUtil {
/**
* 改变 EditText 游标的颜色
*/
public static void setCursorTint(@NonNull EditText editText, @ColorInt int color) {
try {
Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
fCursorDrawableRes.setAccessible(true);
int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);
Field fEditor = TextView.class.getDeclaredField("mEditor");
fEditor.setAccessible(true);
Object editor = fEditor.get(editText);
Class> clazz = editor.getClass();
Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
fCursorDrawable.setAccessible(true);
Drawable[] drawables = new Drawable[2];
drawables[0] = ContextCompat.getDrawable(editText.getContext(), mCursorDrawableRes);
drawables[1] = ContextCompat.getDrawable(editText.getContext(), mCursorDrawableRes);
drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
fCursorDrawable.set(editor, drawables);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setTint(@NonNull FloatingActionButton floatingActionButton, @ColorInt int color) {
int[] colors = new int[]{color, color, color, color, color, color};
int[][] states = new int[6][];
states[0] = new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled};
states[1] = new int[]{android.R.attr.state_enabled, android.R.attr.state_focused};
states[2] = new int[]{android.R.attr.state_enabled};
states[3] = new int[]{android.R.attr.state_focused};
states[4] = new int[]{android.R.attr.state_window_focused};
states[5] = new int[]{};
floatingActionButton.setBackgroundTintList(new ColorStateList(states, colors));
}
public static void setTint(@NonNull SwitchCompat switchCompat, @ColorInt int color) {
int[] colors = new int[]{color, Color.rgb(236, 236, 236), Color.rgb(236, 236, 236), Color.rgb(236, 236, 236), Color.rgb(236, 236, 236), Color.rgb(236, 236, 236)};
int[][] states = new int[6][];
states[0] = new int[]{android.R.attr.state_checked, android.R.attr.state_enabled};
states[1] = new int[]{android.R.attr.state_enabled, android.R.attr.state_focused};
states[2] = new int[]{android.R.attr.state_enabled};
states[3] = new int[]{android.R.attr.state_focused};
states[4] = new int[]{android.R.attr.state_window_focused};
states[5] = new int[]{};
switchCompat.setThumbTintList(new ColorStateList(states, colors));
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/PackageUtil.java
================================================
package me.bakumon.ugank.utills;
import android.content.Context;
import android.content.pm.PackageManager;
/**
* PackageUtil
* Created by bakumon on 2016/12/29 11:01.
*/
public class PackageUtil {
public static String getVersionName(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return "";
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/utills/StatusBarUtil.java
================================================
package me.bakumon.ugank.utills;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.support.annotation.FloatRange;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* 状态栏
* Created by bakumon on 17-7-8.
*/
@SuppressWarnings("unused")
public class StatusBarUtil {
public static int DEFAULT_COLOR = 0;
public static float DEFAULT_ALPHA = 0;//Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 0.2f : 0.3f;
//
public static void immersive(Activity activity) {
immersive(activity, DEFAULT_COLOR, DEFAULT_ALPHA);
}
public static void immersive(Activity activity, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) {
immersive(activity.getWindow(), color, alpha);
}
public static void immersive(Activity activity, int color) {
immersive(activity.getWindow(), color, 1f);
}
public static void immersive(Window window) {
immersive(window, DEFAULT_COLOR, DEFAULT_ALPHA);
}
public static void immersive(Window window, int color) {
immersive(window, color, 1f);
}
public static void immersive(Window window, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) {
if (Build.VERSION.SDK_INT >= 21) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(mixtureColor(color, alpha));
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
} else if (Build.VERSION.SDK_INT >= 19) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
setTranslucentView((ViewGroup) window.getDecorView(), color, alpha);
} else if (Build.VERSION.SDK_INT >= 16) {
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
}
}
//
//
public static void darkMode(Activity activity, boolean dark) {
if (isFlyme4Later()) {
darkModeForFlyme4(activity.getWindow(), dark);
} else if (isMIUI6Later()) {
darkModeForMIUI6(activity.getWindow(), dark);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
darkModeForM(activity.getWindow(), dark);
}
}
/** 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */
public static void darkMode(Activity activity) {
darkMode(activity.getWindow(), DEFAULT_COLOR, DEFAULT_ALPHA);
}
public static void darkMode(Activity activity, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) {
darkMode(activity.getWindow(), color, alpha);
}
/** 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */
public static void darkMode(Window window, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) {
if (isFlyme4Later()) {
immersive(window,color,alpha);
darkModeForFlyme4(window, true);
} else if (isMIUI6Later()) {
immersive(window,color,alpha);
darkModeForMIUI6(window, true);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
immersive(window, color, alpha);
darkModeForM(window, true);
} else if (Build.VERSION.SDK_INT >= 19) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
setTranslucentView((ViewGroup) window.getDecorView(), color, alpha);
}
// if (Build.VERSION.SDK_INT >= 21) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// window.setStatusBarColor(Color.TRANSPARENT);
// } else if (Build.VERSION.SDK_INT >= 19) {
// window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// }
// setTranslucentView((ViewGroup) window.getDecorView(), color, alpha);
}
//------------------------->
/** android 6.0设置字体颜色 */
private static void darkModeForM(Window window, boolean dark) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// window.setStatusBarColor(Color.TRANSPARENT);
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
if (dark) {
systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else {
systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
}
/**
* 设置Flyme4+的darkMode,darkMode时候字体颜色及icon变黑
* http://open-wiki.flyme.cn/index.php?title=Flyme%E7%B3%BB%E7%BB%9FAPI
*/
public static boolean darkModeForFlyme4(Window window, boolean dark) {
boolean result = false;
if (window != null) {
try {
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class
.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
result = true;
} catch (Exception var8) {
Log.e("StatusBar", "darkIcon: failed");
}
}
return result;
}
/**
* 设置MIUI6+的状态栏是否为darkMode,darkMode时候字体颜色及icon变黑
* http://dev.xiaomi.com/doc/p=4769/
*/
public static boolean darkModeForMIUI6(Window window, boolean darkmode) {
Class extends Window> clazz = window.getClass();
try {
int darkModeFlag = 0;
Class> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
extraFlagField.invoke(window, darkmode ? darkModeFlag : 0, darkModeFlag);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/** 判断是否Flyme4以上 */
public static boolean isFlyme4Later() {
return Build.FINGERPRINT.contains("Flyme_OS")
|| Build.VERSION.INCREMENTAL.contains("Flyme_OS")
|| Pattern.compile("Flyme OS [4|5]", Pattern.CASE_INSENSITIVE).matcher(Build.DISPLAY).find()
|| Pattern.compile("Flyme", Pattern.CASE_INSENSITIVE).matcher(Build.DISPLAY).find()
|| Build.FINGERPRINT.contains("Meizu");
}
/** 判断是否为MIUI6以上 */
public static boolean isMIUI6Later() {
try {
Class> clz = Class.forName("android.os.SystemProperties");
Method mtd = clz.getMethod("get", String.class);
String val = (String) mtd.invoke(null, "ro.miui.ui.version.name");
val = val.replaceAll("[vV]", "");
int version = Integer.parseInt(val);
return version >= 6;
} catch (Exception e) {
return false;
}
}
//
/** 增加View的paddingTop,增加的值为状态栏高度 */
public static void setPadding(Context context, View view) {
if (Build.VERSION.SDK_INT >= 16) {
view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context),
view.getPaddingRight(), view.getPaddingBottom());
}
}
/** 增加View的paddingTop,增加的值为状态栏高度 (智能判断,并设置高度)*/
public static void setPaddingSmart(Context context, View view) {
if (Build.VERSION.SDK_INT >= 16) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp != null && lp.height > 0) {
lp.height += getStatusBarHeight(context);//增高
}
view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context),
view.getPaddingRight(), view.getPaddingBottom());
}
}
/** 增加View的高度以及paddingTop,增加的值为状态栏高度.一般是在沉浸式全屏给ToolBar用的 */
public static void setHeightAndPadding(Context context, View view) {
if (Build.VERSION.SDK_INT >= 16) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
lp.height += getStatusBarHeight(context);//增高
view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context),
view.getPaddingRight(), view.getPaddingBottom());
}
}
/** 增加View上边距(MarginTop)一般是给高度为 WARP_CONTENT 的小控件用的*/
public static void setMargin(Context context, View view) {
if (Build.VERSION.SDK_INT >= 16) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp instanceof ViewGroup.MarginLayoutParams) {
((ViewGroup.MarginLayoutParams) lp).topMargin += getStatusBarHeight(context);//增高
}
view.setLayoutParams(lp);
}
}
/**
* 创建假的透明栏
*/
public static void setTranslucentView(ViewGroup container, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) {
if (Build.VERSION.SDK_INT >= 19) {
int mixtureColor = mixtureColor(color, alpha);
View translucentView = container.findViewById(android.R.id.custom);
if (translucentView == null && mixtureColor != 0) {
translucentView = new View(container.getContext());
translucentView.setId(android.R.id.custom);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext()));
container.addView(translucentView, lp);
}
if (translucentView != null) {
translucentView.setBackgroundColor(mixtureColor);
}
}
}
public static int mixtureColor(int color, @FloatRange(from = 0.0, to = 1.0) float alpha) {
int a = (color & 0xff000000) == 0 ? 0xff : color >>> 24;
return (color & 0x00ffffff) | (((int) (a * alpha)) << 24);
}
/** 获取状态栏高度 */
public static int getStatusBarHeight(Context context) {
int result = 24;
int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
result = context.getResources().getDimensionPixelSize(resId);
} else {
result = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
result, Resources.getSystem().getDisplayMetrics());
}
return result;
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/AboutDialog.java
================================================
package me.bakumon.ugank.widget;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import me.bakumon.ugank.R;
import me.bakumon.ugank.base.BaseDialog;
/**
* AboutDialog
* Created by bakumon on 2016/12/29.
*/
public class AboutDialog extends BaseDialog {
@BindView(R.id.tv_affirm)
TextView mTvAffirm;
@BindView(R.id.tv_author_github)
TextView mTvAuthorGithub;
@BindView(R.id.tv_author_weibo)
TextView getmTvAuthorWeibo;
@BindView(R.id.tv_open_address)
TextView mTvOpenAddress;
@BindView(R.id.tv_thanks)
TextView mTvThanks;
@BindView(R.id.tv_gankio)
TextView mTvGankio;
private int mThemeColor;
private Activity mContext;
public AboutDialog(Context context, int layoutId) {
super(context, layoutId, R.style.MyDialog);
}
public AboutDialog(Activity context) {
super(context, R.layout.dialog_about, R.style.MyDialog);
}
public AboutDialog(Activity context, int color) {
this(context);
mContext = context;
mThemeColor = color;
initView();
}
private void initView() {
mTvAffirm.setTextColor(mThemeColor);
mTvAuthorGithub.setTextColor(mThemeColor);
getmTvAuthorWeibo.setTextColor(mThemeColor);
mTvOpenAddress.setTextColor(mThemeColor);
mTvThanks.setTextColor(mThemeColor);
mTvGankio.setTextColor(mThemeColor);
setUnderline(mTvOpenAddress);
setUnderline(mTvGankio);
setUnderline(mTvAuthorGithub);
setUnderline(getmTvAuthorWeibo);
}
private void setUnderline(TextView textView) {
textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
textView.getPaint().setAntiAlias(true);//抗锯齿
}
@OnClick(R.id.tv_affirm)
public void affirm() {
cancel();
}
@OnClick(R.id.tv_thanks)
public void thanks() {
viewIntent("http://weibo.com/daimajia");
}
@OnClick(R.id.tv_open_address)
public void openAddress() {
viewIntent("https://github.com/Bakumon/UGank");
}
@OnClick(R.id.tv_gankio)
public void gankio() {
viewIntent("http://gank.io/");
}
@OnClick(R.id.tv_author_github)
public void github() {
viewIntent("https://github.com/Bakumon/");
}
@OnClick(R.id.tv_author_weibo)
public void weibo() {
viewIntent("http://weibo.com/twimb/");
}
private void viewIntent(String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
mContext.startActivity(intent);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/ObservableWebView.java
================================================
package me.bakumon.ugank.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
public class ObservableWebView extends WebView {
private OnScrollChangedCallback mOnScrollChangedCallback;
public ObservableWebView(final Context context) {
super(context);
}
public ObservableWebView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public ObservableWebView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onScrollChanged(final int l, final int t, final int oldl,
final int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mOnScrollChangedCallback != null) {
mOnScrollChangedCallback.onScroll(l - oldl, t - oldt);
}
}
public void setOnScrollChangedCallback(
final OnScrollChangedCallback onScrollChangedCallback) {
mOnScrollChangedCallback = onScrollChangedCallback;
}
public interface OnScrollChangedCallback {
void onScroll(int dx, int dy);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/PinchImageView.java
================================================
package me.bakumon.ugank.widget;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 手势图片控件
*
* @author clifford
*/
public class PinchImageView extends ImageView {
////////////////////////////////配置参数////////////////////////////////
/**
* 图片缩放动画时间
*/
public static final int SCALE_ANIMATOR_DURATION = 200;
/**
* 惯性动画衰减参数
*/
public static final float FLING_DAMPING_FACTOR = 0.9f;
/**
* 图片最大放大比例
*/
private static final float MAX_SCALE = 4f;
////////////////////////////////监听器////////////////////////////////
/**
* 外界点击事件
*
* @see #setOnClickListener(OnClickListener)
*/
private OnClickListener mOnClickListener;
/**
* 外界长按事件
*
* @see #setOnLongClickListener(OnLongClickListener)
*/
private OnLongClickListener mOnLongClickListener;
@Override
public void setOnClickListener(OnClickListener l) {
//默认的click会在任何点击情况下都会触发,所以搞成自己的
mOnClickListener = l;
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
//默认的long click会在任何长按情况下都会触发,所以搞成自己的
mOnLongClickListener = l;
}
////////////////////////////////公共状态获取////////////////////////////////
/**
* 手势状态:自由状态
*
* @see #getPinchMode()
*/
public static final int PINCH_MODE_FREE = 0;
/**
* 手势状态:单指滚动状态
*
* @see #getPinchMode()
*/
public static final int PINCH_MODE_SCROLL = 1;
/**
* 手势状态:双指缩放状态
*
* @see #getPinchMode()
*/
public static final int PINCH_MODE_SCALE = 2;
/**
* 外层变换矩阵,如果是单位矩阵,那么图片是fit center状态
*
* @see #getOuterMatrix(Matrix)
* @see #outerMatrixTo(Matrix, long)
*/
private Matrix mOuterMatrix = new Matrix();
/**
* 矩形遮罩
*
* @see #getMask()
* @see #zoomMaskTo(RectF, long)
*/
private RectF mMask;
/**
* 当前手势状态
*
* @see #getPinchMode()
* @see #PINCH_MODE_FREE
* @see #PINCH_MODE_SCROLL
* @see #PINCH_MODE_SCALE
*/
private int mPinchMode = PINCH_MODE_FREE;
/**
* 获取外部变换矩阵.
*
* 外部变换矩阵记录了图片手势操作的最终结果,是相对于图片fit center状态的变换.
* 默认值为单位矩阵,此时图片为fit center状态.
*
* @param matrix 用于填充结果的对象
* @return 如果传了matrix参数则将matrix填充后返回,否则new一个填充返回
*/
public Matrix getOuterMatrix(Matrix matrix) {
if (matrix == null) {
matrix = new Matrix(mOuterMatrix);
} else {
matrix.set(mOuterMatrix);
}
return matrix;
}
/**
* 获取内部变换矩阵.
*
* 内部变换矩阵是原图到fit center状态的变换,当原图尺寸变化或者控件大小变化都会发生改变
* 当尚未布局或者原图不存在时,其值无意义.所以在调用前需要确保前置条件有效,否则将影响计算结果.
*
* @param matrix 用于填充结果的对象
* @return 如果传了matrix参数则将matrix填充后返回,否则new一个填充返回
*/
public Matrix getInnerMatrix(Matrix matrix) {
if (matrix == null) {
matrix = new Matrix();
} else {
matrix.reset();
}
if (isReady()) {
//原图大小
RectF tempSrc = MathUtils.rectFTake(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
//控件大小
RectF tempDst = MathUtils.rectFTake(0, 0, getWidth(), getHeight());
//计算fit center矩阵
matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.CENTER);
//释放临时对象
MathUtils.rectFGiven(tempDst);
MathUtils.rectFGiven(tempSrc);
}
return matrix;
}
/**
* 获取图片总变换矩阵.
*
* 总变换矩阵为内部变换矩阵x外部变换矩阵,决定了原图到所见最终状态的变换
* 当尚未布局或者原图不存在时,其值无意义.所以在调用前需要确保前置条件有效,否则将影响计算结果.
*
* @param matrix 用于填充结果的对象
* @return 如果传了matrix参数则将matrix填充后返回,否则new一个填充返回
*
* @see #getOuterMatrix(Matrix)
* @see #getInnerMatrix(Matrix)
*/
public Matrix getCurrentImageMatrix(Matrix matrix) {
//获取内部变换矩阵
matrix = getInnerMatrix(matrix);
//乘上外部变换矩阵
matrix.postConcat(mOuterMatrix);
return matrix;
}
/**
* 获取当前变换后的图片位置和尺寸
*
* 当尚未布局或者原图不存在时,其值无意义.所以在调用前需要确保前置条件有效,否则将影响计算结果.
*
* @param rectF 用于填充结果的对象
* @return 如果传了rectF参数则将rectF填充后返回,否则new一个填充返回
*
* @see #getCurrentImageMatrix(Matrix)
*/
public RectF getImageBound(RectF rectF) {
if (rectF == null) {
rectF = new RectF();
} else {
rectF.setEmpty();
}
if (!isReady()) {
return rectF;
} else {
//申请一个空matrix
Matrix matrix = MathUtils.matrixTake();
//获取当前总变换矩阵
getCurrentImageMatrix(matrix);
//对原图矩形进行变换得到当前显示矩形
rectF.set(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
matrix.mapRect(rectF);
//释放临时matrix
MathUtils.matrixGiven(matrix);
return rectF;
}
}
/**
* 获取当前设置的mask
*
* @return 返回当前的mask对象副本,如果当前没有设置mask则返回null
*/
public RectF getMask() {
if (mMask != null) {
return new RectF(mMask);
} else {
return null;
}
}
/**
* 获取当前手势状态
*
* @see #PINCH_MODE_FREE
* @see #PINCH_MODE_SCROLL
* @see #PINCH_MODE_SCALE
*/
public int getPinchMode() {
return mPinchMode;
}
////////////////////////////////公共状态设置////////////////////////////////
/**
* 执行当前outerMatrix到指定outerMatrix渐变的动画
*
* 调用此方法会停止正在进行中的手势以及手势动画.
* 当duration为0时,outerMatrix值会被立即设置而不会启动动画.
*
* @param endMatrix 动画目标矩阵
* @param duration 动画持续时间
*
* @see #getOuterMatrix(Matrix)
*/
public void outerMatrixTo(Matrix endMatrix, long duration) {
if (endMatrix == null) {
return;
}
//将手势设置为PINCH_MODE_FREE将停止后续手势的触发
mPinchMode = PINCH_MODE_FREE;
//停止所有正在进行的动画
cancelAllAnimator();
//如果时间不合法立即执行结果
if (duration <= 0) {
mOuterMatrix.set(endMatrix);
dispatchOuterMatrixChanged();
invalidate();
} else {
//创建矩阵变化动画
mScaleAnimator = new ScaleAnimator(mOuterMatrix, endMatrix, duration);
mScaleAnimator.start();
}
}
/**
* 执行当前mask到指定mask的变化动画
*
* 调用此方法不会停止手势以及手势相关动画,但会停止正在进行的mask动画.
* 当前mask为null时,则不执行动画立即设置为目标mask.
* 当duration为0时,立即将当前mask设置为目标mask,不会执行动画.
*
* @param mask 动画目标mask
* @param duration 动画持续时间
*
* @see #getMask()
*/
public void zoomMaskTo(RectF mask, long duration) {
if (mask == null) {
return;
}
//停止mask动画
if (mMaskAnimator != null) {
mMaskAnimator.cancel();
mMaskAnimator = null;
}
//如果duration为0或者之前没有设置过mask,不执行动画,立即设置
if (duration <= 0 || mMask == null) {
if (mMask == null) {
mMask = new RectF();
}
mMask.set(mask);
invalidate();
} else {
//执行mask动画
mMaskAnimator = new MaskAnimator(mMask, mask, duration);
mMaskAnimator.start();
}
}
/**
* 重置所有状态
*
* 重置位置到fit center状态,清空mask,停止所有手势,停止所有动画.
* 但不清空drawable,以及事件绑定相关数据.
*/
public void reset() {
//重置位置到fit
mOuterMatrix.reset();
dispatchOuterMatrixChanged();
//清空mask
mMask = null;
//停止所有手势
mPinchMode = PINCH_MODE_FREE;
mLastMovePoint.set(0, 0);
mScaleCenter.set(0, 0);
mScaleBase = 0;
//停止所有动画
if (mMaskAnimator != null) {
mMaskAnimator.cancel();
mMaskAnimator = null;
}
cancelAllAnimator();
//重绘
invalidate();
}
////////////////////////////////对外广播事件////////////////////////////////
/**
* 外部矩阵变化事件通知监听器
*/
public interface OuterMatrixChangedListener {
/**
* 外部矩阵变化回调
*
* 外部矩阵的任何变化后都收到此回调.
* 外部矩阵变化后,总变化矩阵,图片的展示位置都将发生变化.
*
* @param pinchImageView
*
* @see #getOuterMatrix(Matrix)
* @see #getCurrentImageMatrix(Matrix)
* @see #getImageBound(RectF)
*/
void onOuterMatrixChanged(PinchImageView pinchImageView);
}
/**
* 所有OuterMatrixChangedListener监听列表
*
* @see #addOuterMatrixChangedListener(OuterMatrixChangedListener)
* @see #removeOuterMatrixChangedListener(OuterMatrixChangedListener)
*/
private List mOuterMatrixChangedListeners;
/**
* 当mOuterMatrixChangedListeners被锁定不允许修改时,临时将修改写到这个副本中
*
* @see #mOuterMatrixChangedListeners
*/
private List mOuterMatrixChangedListenersCopy;
/**
* mOuterMatrixChangedListeners的修改锁定
*
* 当进入dispatchOuterMatrixChanged方法时,被加1,退出前被减1
*
* @see #dispatchOuterMatrixChanged()
* @see #addOuterMatrixChangedListener(OuterMatrixChangedListener)
* @see #removeOuterMatrixChangedListener(OuterMatrixChangedListener)
*/
private int mDispatchOuterMatrixChangedLock;
/**
* 添加外部矩阵变化监听
*
* @param listener
*/
public void addOuterMatrixChangedListener(OuterMatrixChangedListener listener) {
if (listener == null) {
return;
}
//如果监听列表没有被修改锁定直接将监听添加到监听列表
if (mDispatchOuterMatrixChangedLock == 0) {
if (mOuterMatrixChangedListeners == null) {
mOuterMatrixChangedListeners = new ArrayList();
}
mOuterMatrixChangedListeners.add(listener);
} else {
//如果监听列表修改被锁定,那么尝试在监听列表副本上添加
//监听列表副本将会在锁定被解除时替换到监听列表里
if (mOuterMatrixChangedListenersCopy == null) {
if (mOuterMatrixChangedListeners != null) {
mOuterMatrixChangedListenersCopy = new ArrayList(mOuterMatrixChangedListeners);
} else {
mOuterMatrixChangedListenersCopy = new ArrayList();
}
}
mOuterMatrixChangedListenersCopy.add(listener);
}
}
/**
* 删除外部矩阵变化监听
*
* @param listener
*/
public void removeOuterMatrixChangedListener(OuterMatrixChangedListener listener) {
if (listener == null) {
return;
}
//如果监听列表没有被修改锁定直接在监听列表数据结构上修改
if (mDispatchOuterMatrixChangedLock == 0) {
if (mOuterMatrixChangedListeners != null) {
mOuterMatrixChangedListeners.remove(listener);
}
} else {
//如果监听列表被修改锁定,那么就在其副本上修改
//其副本将会在锁定解除时替换回监听列表
if (mOuterMatrixChangedListenersCopy == null) {
if (mOuterMatrixChangedListeners != null) {
mOuterMatrixChangedListenersCopy = new ArrayList(mOuterMatrixChangedListeners);
}
}
if (mOuterMatrixChangedListenersCopy != null) {
mOuterMatrixChangedListenersCopy.remove(listener);
}
}
}
/**
* 触发外部矩阵修改事件
*
* 需要在每次给外部矩阵设置值时都调用此方法.
*
* @see #mOuterMatrix
*/
private void dispatchOuterMatrixChanged() {
if (mOuterMatrixChangedListeners == null) {
return;
}
//增加锁
//这里之所以用计数器做锁定是因为可能在锁定期间又间接调用了此方法产生递归
//使用boolean无法判断递归结束
mDispatchOuterMatrixChangedLock++;
//在列表循环过程中不允许修改列表,否则将引发崩溃
for (OuterMatrixChangedListener listener : mOuterMatrixChangedListeners) {
listener.onOuterMatrixChanged(this);
}
//减锁
mDispatchOuterMatrixChangedLock--;
//如果是递归的情况,mDispatchOuterMatrixChangedLock可能大于1,只有减到0才能算列表的锁定解除
if (mDispatchOuterMatrixChangedLock == 0) {
//如果期间有修改列表,那么副本将不为null
if (mOuterMatrixChangedListenersCopy != null) {
//将副本替换掉正式的列表
mOuterMatrixChangedListeners = mOuterMatrixChangedListenersCopy;
//清空副本
mOuterMatrixChangedListenersCopy = null;
}
}
}
////////////////////////////////用于重载定制////////////////////////////////
/**
* 获取图片最大可放大的比例
*
* 如果放大大于这个比例则不被允许.
* 在双手缩放过程中如果图片放大比例大于这个值,手指释放将回弹到这个比例.
* 在双击放大过程中不允许放大比例大于这个值.
* 覆盖此方法可以定制不同情况使用不同的最大可放大比例.
*
* @return 缩放比例
*
* @see #scaleEnd()
* @see #doubleTap(float, float)
*/
protected float getMaxScale() {
return MAX_SCALE;
}
/**
* 计算双击之后图片接下来应该被缩放的比例
*
* 如果值大于getMaxScale或者小于fit center尺寸,则实际使用取边界值.
* 通过覆盖此方法可以定制不同的图片被双击时使用不同的放大策略.
*
* @param innerScale 当前内部矩阵的缩放值
* @param outerScale 当前外部矩阵的缩放值
* @return 接下来的缩放比例
*
* @see #doubleTap(float, float)
* @see #getMaxScale()
*/
protected float calculateNextScale(float innerScale, float outerScale) {
float currentScale = innerScale * outerScale;
if (currentScale < MAX_SCALE) {
return MAX_SCALE;
} else {
return innerScale;
}
}
////////////////////////////////初始化////////////////////////////////
public PinchImageView(Context context) {
super(context);
initView();
}
public PinchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public PinchImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView() {
//强制设置图片scaleType为matrix
super.setScaleType(ScaleType.MATRIX);
}
//不允许设置scaleType,只能用内部设置的matrix
@Override
public void setScaleType(ScaleType scaleType) {}
////////////////////////////////绘制////////////////////////////////
@Override
protected void onDraw(Canvas canvas) {
//在绘制前设置变换矩阵
if (isReady()) {
Matrix matrix = MathUtils.matrixTake();
setImageMatrix(getCurrentImageMatrix(matrix));
MathUtils.matrixGiven(matrix);
}
//对图像做遮罩处理
if (mMask != null) {
canvas.save();
canvas.clipRect(mMask);
super.onDraw(canvas);
canvas.restore();
} else {
super.onDraw(canvas);
}
}
////////////////////////////////有效性判断////////////////////////////////
/**
* 判断当前情况是否能执行手势相关计算
*
* 包括:是否有图片,图片是否有尺寸,控件是否有尺寸.
*
* @return 是否能执行手势相关计算
*/
private boolean isReady() {
return getDrawable() != null && getDrawable().getIntrinsicWidth() > 0 && getDrawable().getIntrinsicHeight() > 0
&& getWidth() > 0 && getHeight() > 0;
}
////////////////////////////////mask动画处理////////////////////////////////
/**
* mask修改的动画
*
* 和图片的动画相互独立.
*
* @see #zoomMaskTo(RectF, long)
*/
private MaskAnimator mMaskAnimator;
/**
* mask变换动画
*
* 将mask从一个rect动画到另外一个rect
*/
private class MaskAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener {
/**
* 开始mask
*/
private float[] mStart = new float[4];
/**
* 结束mask
*/
private float[] mEnd = new float[4];
/**
* 中间结果mask
*/
private float[] mResult = new float[4];
/**
* 创建mask变换动画
*
* @param start 动画起始状态
* @param end 动画终点状态
* @param duration 动画持续时间
*/
public MaskAnimator(RectF start, RectF end, long duration) {
super();
setFloatValues(0, 1f);
setDuration(duration);
addUpdateListener(this);
//将起点终点拷贝到数组方便计算
mStart[0] = start.left;
mStart[1] = start.top;
mStart[2] = start.right;
mStart[3] = start.bottom;
mEnd[0] = end.left;
mEnd[1] = end.top;
mEnd[2] = end.right;
mEnd[3] = end.bottom;
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//获取动画进度,0-1范围
float value = (Float) animation.getAnimatedValue();
//根据进度对起点终点之间做插值
for (int i = 0; i < 4; i++) {
mResult[i] = mStart[i] + (mEnd[i] - mStart[i]) * value;
}
//期间mask有可能被置空了,所以判断一下
if (mMask == null) {
mMask = new RectF();
}
//设置新的mask并绘制
mMask.set(mResult[0], mResult[1], mResult[2], mResult[3]);
invalidate();
}
}
////////////////////////////////手势动画处理////////////////////////////////
/**
* 在单指模式下:
* 记录上一次手指的位置,用于计算新的位置和上一次位置的差值.
*
* 双指模式下:
* 记录两个手指的中点,作为和mScaleCenter绑定的点.
* 这个绑定可以保证mScaleCenter无论如何都会跟随这个中点.
*
* @see #mScaleCenter
* @see #scale(PointF, float, float, PointF)
* @see #scaleEnd()
*/
private PointF mLastMovePoint = new PointF();
/**
* 缩放模式下图片的缩放中点.
*
* 为其指代的点经过innerMatrix变换之后的值.
* 其指代的点在手势过程中始终跟随mLastMovePoint.
* 通过双指缩放时,其为缩放中心点.
*
* @see #saveScaleContext(float, float, float, float)
* @see #mLastMovePoint
* @see #scale(PointF, float, float, PointF)
*/
private PointF mScaleCenter = new PointF();
/**
* 缩放模式下的基础缩放比例
*
* 为外层缩放值除以开始缩放时两指距离.
* 其值乘上最新的两指之间距离为最新的图片缩放比例.
*
* @see #saveScaleContext(float, float, float, float)
* @see #scale(PointF, float, float, PointF)
*/
private float mScaleBase = 0;
/**
* 图片缩放动画
*
* 缩放模式把图片的位置大小超出限制之后触发.
* 双击图片放大或缩小时触发.
* 手动调用outerMatrixTo触发.
*
* @see #scaleEnd()
* @see #doubleTap(float, float)
* @see #outerMatrixTo(Matrix, long)
*/
private ScaleAnimator mScaleAnimator;
/**
* 滑动产生的惯性动画
*
* @see #fling(float, float)
*/
private FlingAnimator mFlingAnimator;
/**
* 常用手势处理
*
* 在onTouchEvent末尾被执行.
*/
private GestureDetector mGestureDetector = new GestureDetector(PinchImageView.this.getContext(), new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//只有在单指模式结束之后才允许执行fling
if (mPinchMode == PINCH_MODE_FREE && !(mScaleAnimator != null && mScaleAnimator.isRunning())) {
fling(velocityX, velocityY);
}
return true;
}
public void onLongPress(MotionEvent e) {
//触发长按
if (mOnLongClickListener != null) {
mOnLongClickListener.onLongClick(PinchImageView.this);
}
}
public boolean onDoubleTap(MotionEvent e) {
//当手指快速第二次按下触发,此时必须是单指模式才允许执行doubleTap
if (mPinchMode == PINCH_MODE_SCROLL && !(mScaleAnimator != null && mScaleAnimator.isRunning())) {
doubleTap(e.getX(), e.getY());
}
return true;
}
public boolean onSingleTapConfirmed(MotionEvent e) {
//触发点击
if (mOnClickListener != null) {
mOnClickListener.onClick(PinchImageView.this);
}
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
int action = event.getAction() & MotionEvent.ACTION_MASK;
//最后一个点抬起或者取消,结束所有模式
if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
//如果之前是缩放模式,还需要触发一下缩放结束动画
if (mPinchMode == PINCH_MODE_SCALE) {
scaleEnd();
}
mPinchMode = PINCH_MODE_FREE;
} else if (action == MotionEvent.ACTION_POINTER_UP) {
//多个手指情况下抬起一个手指,此时需要是缩放模式才触发
if (mPinchMode == PINCH_MODE_SCALE) {
//抬起的点如果大于2,那么缩放模式还有效,但是有可能初始点变了,重新测量初始点
if (event.getPointerCount() > 2) {
//如果还没结束缩放模式,但是第一个点抬起了,那么让第二个点和第三个点作为缩放控制点
if (event.getAction() >> 8 == 0) {
saveScaleContext(event.getX(1), event.getY(1), event.getX(2), event.getY(2));
//如果还没结束缩放模式,但是第二个点抬起了,那么让第一个点和第三个点作为缩放控制点
} else if (event.getAction() >> 8 == 1) {
saveScaleContext(event.getX(0), event.getY(0), event.getX(2), event.getY(2));
}
}
//如果抬起的点等于2,那么此时只剩下一个点,也不允许进入单指模式,因为此时可能图片没有在正确的位置上
}
//第一个点按下,开启滚动模式,记录开始滚动的点
} else if (action == MotionEvent.ACTION_DOWN) {
//在矩阵动画过程中不允许启动滚动模式
if (!(mScaleAnimator != null && mScaleAnimator.isRunning())) {
//停止所有动画
cancelAllAnimator();
//切换到滚动模式
mPinchMode = PINCH_MODE_SCROLL;
//保存触发点用于move计算差值
mLastMovePoint.set(event.getX(), event.getY());
}
//非第一个点按下,关闭滚动模式,开启缩放模式,记录缩放模式的一些初始数据
} else if (action == MotionEvent.ACTION_POINTER_DOWN) {
//停止所有动画
cancelAllAnimator();
//切换到缩放模式
mPinchMode = PINCH_MODE_SCALE;
//保存缩放的两个手指
saveScaleContext(event.getX(0), event.getY(0), event.getX(1), event.getY(1));
} else if (action == MotionEvent.ACTION_MOVE) {
if (!(mScaleAnimator != null && mScaleAnimator.isRunning())) {
//在滚动模式下移动
if (mPinchMode == PINCH_MODE_SCROLL) {
//每次移动产生一个差值累积到图片位置上
scrollBy(event.getX() - mLastMovePoint.x, event.getY() - mLastMovePoint.y);
//记录新的移动点
mLastMovePoint.set(event.getX(), event.getY());
//在缩放模式下移动
} else if (mPinchMode == PINCH_MODE_SCALE && event.getPointerCount() > 1) {
//两个缩放点间的距离
float distance = MathUtils.getDistance(event.getX(0), event.getY(0), event.getX(1), event.getY(1));
//保存缩放点中点
float[] lineCenter = MathUtils.getCenterPoint(event.getX(0), event.getY(0), event.getX(1), event.getY(1));
mLastMovePoint.set(lineCenter[0], lineCenter[1]);
//处理缩放
scale(mScaleCenter, mScaleBase, distance, mLastMovePoint);
}
}
}
//无论如何都处理各种外部手势
mGestureDetector.onTouchEvent(event);
return true;
}
/**
* 让图片移动一段距离
*
* 不能移动超过可移动范围,超过了就到可移动范围边界为止.
*
* @param xDiff 移动距离
* @param yDiff 移动距离
* @return 是否改变了位置
*/
private boolean scrollBy(float xDiff, float yDiff) {
if (!isReady()) {
return false;
}
//原图方框
RectF bound = MathUtils.rectFTake();
getImageBound(bound);
//控件大小
float displayWidth = getWidth();
float displayHeight = getHeight();
//如果当前图片宽度小于控件宽度,则不能移动
if (bound.right - bound.left < displayWidth) {
xDiff = 0;
//如果图片左边在移动后超出控件左边
} else if (bound.left + xDiff > 0) {
//如果在移动之前是没超出的,计算应该移动的距离
if (bound.left < 0) {
xDiff = -bound.left;
//否则无法移动
} else {
xDiff = 0;
}
//如果图片右边在移动后超出控件右边
} else if (bound.right + xDiff < displayWidth) {
//如果在移动之前是没超出的,计算应该移动的距离
if (bound.right > displayWidth) {
xDiff = displayWidth - bound.right;
//否则无法移动
} else {
xDiff = 0;
}
}
//以下同理
if (bound.bottom - bound.top < displayHeight) {
yDiff = 0;
} else if (bound.top + yDiff > 0) {
if (bound.top < 0) {
yDiff = -bound.top;
} else {
yDiff = 0;
}
} else if (bound.bottom + yDiff < displayHeight) {
if (bound.bottom > displayHeight) {
yDiff = displayHeight - bound.bottom;
} else {
yDiff = 0;
}
}
MathUtils.rectFGiven(bound);
//应用移动变换
mOuterMatrix.postTranslate(xDiff, yDiff);
dispatchOuterMatrixChanged();
//触发重绘
invalidate();
//检查是否有变化
if (xDiff != 0 || yDiff != 0) {
return true;
} else {
return false;
}
}
/**
* 记录缩放前的一些信息
*
* 保存基础缩放值.
* 保存图片缩放中点.
*
* @param x1 缩放第一个手指
* @param y1 缩放第一个手指
* @param x2 缩放第二个手指
* @param y2 缩放第二个手指
*/
private void saveScaleContext(float x1, float y1, float x2, float y2) {
//记录基础缩放值,其中图片缩放比例按照x方向来计算
//理论上图片应该是等比的,x和y方向比例相同
//但是有可能外部设定了不规范的值.
//但是后续的scale操作会将xy不等的缩放值纠正,改成和x方向相同
mScaleBase = MathUtils.getMatrixScale(mOuterMatrix)[0] / MathUtils.getDistance(x1, y1, x2, y2);
//两手指的中点在屏幕上落在了图片的某个点上,图片上的这个点在经过总矩阵变换后和手指中点相同
//现在我们需要得到图片上这个点在图片是fit center状态下在屏幕上的位置
//因为后续的计算都是基于图片是fit center状态下进行变换
//所以需要把两手指中点除以外层变换矩阵得到mScaleCenter
float[] center = MathUtils.inverseMatrixPoint(MathUtils.getCenterPoint(x1, y1, x2, y2), mOuterMatrix);
mScaleCenter.set(center[0], center[1]);
}
/**
* 对图片按照一些手势信息进行缩放
*
* @param scaleCenter mScaleCenter
* @param scaleBase mScaleBase
* @param distance 手指两点之间距离
* @param lineCenter 手指两点之间中点
*
* @see #mScaleCenter
* @see #mScaleBase
*/
private void scale(PointF scaleCenter, float scaleBase, float distance, PointF lineCenter) {
if (!isReady()) {
return;
}
//计算图片从fit center状态到目标状态的缩放比例
float scale = scaleBase * distance;
Matrix matrix = MathUtils.matrixTake();
//按照图片缩放中心缩放,并且让缩放中心在缩放点中点上
matrix.postScale(scale, scale, scaleCenter.x, scaleCenter.y);
//让图片的缩放中点跟随手指缩放中点
matrix.postTranslate(lineCenter.x - scaleCenter.x, lineCenter.y - scaleCenter.y);
//应用变换
mOuterMatrix.set(matrix);
MathUtils.matrixGiven(matrix);
dispatchOuterMatrixChanged();
//重绘
invalidate();
}
/**
* 双击后放大或者缩小
*
* 将图片缩放比例缩放到nextScale指定的值.
* 但nextScale值不能大于最大缩放值不能小于fit center情况下的缩放值.
* 将双击的点尽量移动到控件中心.
*
* @param x 双击的点
* @param y 双击的点
*
* @see #calculateNextScale(float, float)
* @see #getMaxScale()
*/
private void doubleTap(float x, float y) {
if (!isReady()) {
return;
}
//获取第一层变换矩阵
Matrix innerMatrix = MathUtils.matrixTake();
getInnerMatrix(innerMatrix);
//当前总的缩放比例
float innerScale = MathUtils.getMatrixScale(innerMatrix)[0];
float outerScale = MathUtils.getMatrixScale(mOuterMatrix)[0];
float currentScale = innerScale * outerScale;
//控件大小
float displayWidth = getWidth();
float displayHeight = getHeight();
//最大放大大小
float maxScale = getMaxScale();
//接下来要放大的大小
float nextScale = calculateNextScale(innerScale, outerScale);
//如果接下来放大大于最大值或者小于fit center值,则取边界
if (nextScale > maxScale) {
nextScale = maxScale;
}
if (nextScale < innerScale) {
nextScale = innerScale;
}
//开始计算缩放动画的结果矩阵
Matrix animEnd = MathUtils.matrixTake(mOuterMatrix);
//计算还需缩放的倍数
animEnd.postScale(nextScale / currentScale, nextScale / currentScale, x, y);
//将放大点移动到控件中心
animEnd.postTranslate(displayWidth / 2f - x, displayHeight / 2f - y);
//得到放大之后的图片方框
Matrix testMatrix = MathUtils.matrixTake(innerMatrix);
testMatrix.postConcat(animEnd);
RectF testBound = MathUtils.rectFTake(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
testMatrix.mapRect(testBound);
//修正位置
float postX = 0;
float postY = 0;
if (testBound.right - testBound.left < displayWidth) {
postX = displayWidth / 2f - (testBound.right + testBound.left) / 2f;
} else if (testBound.left > 0) {
postX = -testBound.left;
} else if (testBound.right < displayWidth) {
postX = displayWidth - testBound.right;
}
if (testBound.bottom - testBound.top < displayHeight) {
postY = displayHeight / 2f - (testBound.bottom + testBound.top) / 2f;
} else if (testBound.top > 0) {
postY = -testBound.top;
} else if (testBound.bottom < displayHeight) {
postY = displayHeight - testBound.bottom;
}
//应用修正位置
animEnd.postTranslate(postX, postY);
//清理当前可能正在执行的动画
cancelAllAnimator();
//启动矩阵动画
mScaleAnimator = new ScaleAnimator(mOuterMatrix, animEnd);
mScaleAnimator.start();
//清理临时变量
MathUtils.rectFGiven(testBound);
MathUtils.matrixGiven(testMatrix);
MathUtils.matrixGiven(animEnd);
MathUtils.matrixGiven(innerMatrix);
}
/**
* 当缩放操作结束动画
*
* 如果图片超过边界,找到最近的位置动画恢复.
* 如果图片缩放尺寸超过最大值或者最小值,找到最近的值动画恢复.
*/
private void scaleEnd() {
if (!isReady()) {
return;
}
//是否修正了位置
boolean change = false;
//获取图片整体的变换矩阵
Matrix currentMatrix = MathUtils.matrixTake();
getCurrentImageMatrix(currentMatrix);
//整体缩放比例
float currentScale = MathUtils.getMatrixScale(currentMatrix)[0];
//第二层缩放比例
float outerScale = MathUtils.getMatrixScale(mOuterMatrix)[0];
//控件大小
float displayWidth = getWidth();
float displayHeight = getHeight();
//最大缩放比例
float maxScale = getMaxScale();
//比例修正
float scalePost = 1f;
//位置修正
float postX = 0;
float postY = 0;
//如果整体缩放比例大于最大比例,进行缩放修正
if (currentScale > maxScale) {
scalePost = maxScale / currentScale;
}
//如果缩放修正后整体导致第二层缩放小于1(就是图片比fit center状态还小),重新修正缩放
if (outerScale * scalePost < 1f) {
scalePost = 1f / outerScale;
}
//如果缩放修正不为1,说明进行了修正
if (scalePost != 1f) {
change = true;
}
//尝试根据缩放点进行缩放修正
Matrix testMatrix = MathUtils.matrixTake(currentMatrix);
testMatrix.postScale(scalePost, scalePost, mLastMovePoint.x, mLastMovePoint.y);
RectF testBound = MathUtils.rectFTake(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
//获取缩放修正后的图片方框
testMatrix.mapRect(testBound);
//检测缩放修正后位置有无超出,如果超出进行位置修正
if (testBound.right - testBound.left < displayWidth) {
postX = displayWidth / 2f - (testBound.right + testBound.left) / 2f;
} else if (testBound.left > 0) {
postX = -testBound.left;
} else if (testBound.right < displayWidth) {
postX = displayWidth - testBound.right;
}
if (testBound.bottom - testBound.top < displayHeight) {
postY = displayHeight / 2f - (testBound.bottom + testBound.top) / 2f;
} else if (testBound.top > 0) {
postY = -testBound.top;
} else if (testBound.bottom < displayHeight) {
postY = displayHeight - testBound.bottom;
}
//如果位置修正不为0,说明进行了修正
if (postX != 0 || postY != 0) {
change = true;
}
//只有有执行修正才执行动画
if (change) {
//计算结束矩阵
Matrix animEnd = MathUtils.matrixTake(mOuterMatrix);
animEnd.postScale(scalePost, scalePost, mLastMovePoint.x, mLastMovePoint.y);
animEnd.postTranslate(postX, postY);
//清理当前可能正在执行的动画
cancelAllAnimator();
//启动矩阵动画
mScaleAnimator = new ScaleAnimator(mOuterMatrix, animEnd);
mScaleAnimator.start();
//清理临时变量
MathUtils.matrixGiven(animEnd);
}
//清理临时变量
MathUtils.rectFGiven(testBound);
MathUtils.matrixGiven(testMatrix);
MathUtils.matrixGiven(currentMatrix);
}
/**
* 执行惯性动画
*
* 动画在遇到不能移动就停止.
* 动画速度衰减到很小就停止.
*
* 其中参数速度单位为 像素/秒
*
* @param vx x方向速度
* @param vy y方向速度
*/
private void fling(float vx, float vy) {
if (!isReady()) {
return;
}
//清理当前可能正在执行的动画
cancelAllAnimator();
//创建惯性动画
//FlingAnimator单位为 像素/帧,一秒60帧
mFlingAnimator = new FlingAnimator(vx / 60f, vy / 60f);
mFlingAnimator.start();
}
/**
* 停止所有手势动画
*/
private void cancelAllAnimator() {
if (mScaleAnimator != null) {
mScaleAnimator.cancel();
mScaleAnimator = null;
}
if (mFlingAnimator != null) {
mFlingAnimator.cancel();
mFlingAnimator = null;
}
}
/**
* 惯性动画
*
* 速度逐渐衰减,每帧速度衰减为原来的FLING_DAMPING_FACTOR,当速度衰减到小于1时停止.
* 当图片不能移动时,动画停止.
*/
private class FlingAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener {
/**
* 速度向量
*/
private float[] mVector;
/**
* 创建惯性动画
*
* 参数单位为 像素/帧
*
* @param vectorX 速度向量
* @param vectorY 速度向量
*/
public FlingAnimator(float vectorX, float vectorY) {
super();
setFloatValues(0, 1f);
setDuration(1000000);
addUpdateListener(this);
mVector = new float[]{vectorX, vectorY};
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//移动图像并给出结果
boolean result = scrollBy(mVector[0], mVector[1]);
//衰减速度
mVector[0] *= FLING_DAMPING_FACTOR;
mVector[1] *= FLING_DAMPING_FACTOR;
//速度太小或者不能移动了就结束
if (!result || MathUtils.getDistance(0, 0, mVector[0], mVector[1]) < 1f) {
animation.cancel();
}
}
}
/**
* 缩放动画
*
* 在给定时间内从一个矩阵的变化逐渐动画到另一个矩阵的变化
*/
private class ScaleAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener {
/**
* 开始矩阵
*/
private float[] mStart = new float[9];
/**
* 结束矩阵
*/
private float[] mEnd = new float[9];
/**
* 中间结果矩阵
*/
private float[] mResult = new float[9];
/**
* 构建一个缩放动画
*
* 从一个矩阵变换到另外一个矩阵
*
* @param start 开始矩阵
* @param end 结束矩阵
*/
public ScaleAnimator(Matrix start, Matrix end) {
this(start, end, SCALE_ANIMATOR_DURATION);
}
/**
* 构建一个缩放动画
*
* 从一个矩阵变换到另外一个矩阵
*
* @param start 开始矩阵
* @param end 结束矩阵
* @param duration 动画时间
*/
public ScaleAnimator(Matrix start, Matrix end, long duration) {
super();
setFloatValues(0, 1f);
setDuration(duration);
addUpdateListener(this);
start.getValues(mStart);
end.getValues(mEnd);
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//获取动画进度
float value = (Float) animation.getAnimatedValue();
//根据动画进度计算矩阵中间插值
for (int i = 0; i < 9; i++) {
mResult[i] = mStart[i] + (mEnd[i] - mStart[i]) * value;
}
//设置矩阵并重绘
mOuterMatrix.setValues(mResult);
dispatchOuterMatrixChanged();
invalidate();
}
}
////////////////////////////////防止内存抖动复用对象////////////////////////////////
/**
* 对象池
*
* 防止频繁new对象产生内存抖动.
* 由于对象池最大长度限制,如果吞度量超过对象池容量,仍然会发生抖动.
* 此时需要增大对象池容量,但是会占用更多内存.
*
* @param 对象池容纳的对象类型
*/
private static abstract class ObjectsPool {
/**
* 对象池的最大容量
*/
private int mSize;
/**
* 对象池队列
*/
private Queue mQueue;
/**
* 创建一个对象池
*
* @param size 对象池最大容量
*/
public ObjectsPool(int size) {
mSize = size;
mQueue = new LinkedList();
}
/**
* 获取一个空闲的对象
*
* 如果对象池为空,则对象池自己会new一个返回.
* 如果对象池内有对象,则取一个已存在的返回.
* take出来的对象用完要记得调用given归还.
* 如果不归还,让然会发生内存抖动,但不会引起泄漏.
*
* @return 可用的对象
*
* @see #given(Object)
*/
public T take() {
//如果池内为空就创建一个
if (mQueue.size() == 0) {
return newInstance();
} else {
//对象池里有就从顶端拿出来一个返回
return resetInstance(mQueue.poll());
}
}
/**
* 归还对象池内申请的对象
*
* 如果归还的对象数量超过对象池容量,那么归还的对象就会被丢弃.
*
* @param obj 归还的对象
*
* @see #take()
*/
public void given(T obj) {
//如果对象池还有空位子就归还对象
if (obj != null && mQueue.size() < mSize) {
mQueue.offer(obj);
}
}
/**
* 实例化对象
*
* @return 创建的对象
*/
abstract protected T newInstance();
/**
* 重置对象
*
* 把对象数据清空到就像刚创建的一样.
*
* @param obj 需要被重置的对象
* @return 被重置之后的对象
*/
abstract protected T resetInstance(T obj);
}
/**
* 矩阵对象池
*/
private static class MatrixPool extends ObjectsPool {
public MatrixPool(int size) {
super(size);
}
@Override
protected Matrix newInstance() {
return new Matrix();
}
@Override
protected Matrix resetInstance(Matrix obj) {
obj.reset();
return obj;
}
}
/**
* 矩形对象池
*/
private static class RectFPool extends ObjectsPool {
public RectFPool(int size) {
super(size);
}
@Override
protected RectF newInstance() {
return new RectF();
}
@Override
protected RectF resetInstance(RectF obj) {
obj.setEmpty();
return obj;
}
}
////////////////////////////////数学计算工具类////////////////////////////////
/**
* 数学计算工具类
*/
public static class MathUtils {
/**
* 矩阵对象池
*/
private static MatrixPool mMatrixPool = new MatrixPool(16);
/**
* 获取矩阵对象
*/
public static Matrix matrixTake() {
return mMatrixPool.take();
}
/**
* 获取某个矩阵的copy
*/
public static Matrix matrixTake(Matrix matrix) {
Matrix result = mMatrixPool.take();
if (matrix != null) {
result.set(matrix);
}
return result;
}
/**
* 归还矩阵对象
*/
public static void matrixGiven(Matrix matrix) {
mMatrixPool.given(matrix);
}
/**
* 矩形对象池
*/
private static RectFPool mRectFPool = new RectFPool(16);
/**
* 获取矩形对象
*/
public static RectF rectFTake() {
return mRectFPool.take();
}
/**
* 按照指定值获取矩形对象
*/
public static RectF rectFTake(float left, float top, float right, float bottom) {
RectF result = mRectFPool.take();
result.set(left, top, right, bottom);
return result;
}
/**
* 获取某个矩形的副本
*/
public static RectF rectFTake(RectF rectF) {
RectF result = mRectFPool.take();
if (rectF != null) {
result.set(rectF);
}
return result;
}
/**
* 归还矩形对象
*/
public static void rectFGiven(RectF rectF) {
mRectFPool.given(rectF);
}
/**
* 获取两点之间距离
*
* @param x1 点1
* @param y1 点1
* @param x2 点2
* @param y2 点2
* @return 距离
*/
public static float getDistance(float x1, float y1, float x2, float y2) {
float x = x1 - x2;
float y = y1 - y2;
return (float) Math.sqrt(x * x + y * y);
}
/**
* 获取两点的中点
*
* @param x1 点1
* @param y1 点1
* @param x2 点2
* @param y2 点2
* @return float[]{x, y}
*/
public static float[] getCenterPoint(float x1, float y1, float x2, float y2) {
return new float[]{(x1 + x2) / 2f, (y1 + y2) / 2f};
}
/**
* 获取矩阵的缩放值
*
* @param matrix 要计算的矩阵
* @return float[]{scaleX, scaleY}
*/
public static float[] getMatrixScale(Matrix matrix) {
if (matrix != null) {
float[] value = new float[9];
matrix.getValues(value);
return new float[]{value[0], value[4]};
} else {
return new float[2];
}
}
/**
* 计算点除以矩阵的值
*
* matrix.mapPoints(unknownPoint) -> point
* 已知point和matrix,求unknownPoint的值.
*
* @param point
* @param matrix
* @return unknownPoint
*/
public static float[] inverseMatrixPoint(float[] point, Matrix matrix) {
if (point != null && matrix != null) {
float[] dst = new float[2];
//计算matrix的逆矩阵
Matrix inverse = matrixTake();
matrix.invert(inverse);
//用逆矩阵变换point到dst,dst就是结果
inverse.mapPoints(dst, point);
//清除临时变量
matrixGiven(inverse);
return dst;
} else {
return new float[2];
}
}
/**
* 计算两个矩形之间的变换矩阵
*
* unknownMatrix.mapRect(to, from)
* 已知from矩形和to矩形,求unknownMatrix
*
* @param from
* @param to
* @param result unknownMatrix
*/
public static void calculateRectTranslateMatrix(RectF from, RectF to, Matrix result) {
if (from == null || to == null || result == null) {
return;
}
if (from.width() == 0 || from.height() == 0) {
return;
}
result.reset();
result.postTranslate(-from.left, -from.top);
result.postScale(to.width() / from.width(), to.height() / from.height());
result.postTranslate(to.left, to.top);
}
/**
* 计算图片在某个ImageView中的显示矩形
*
* @param container ImageView的Rect
* @param srcWidth 图片的宽度
* @param srcHeight 图片的高度
* @param scaleType 图片在ImageView中的ScaleType
* @param result 图片应该在ImageView中展示的矩形
*/
public static void calculateScaledRectInContainer(RectF container, float srcWidth, float srcHeight, ScaleType scaleType, RectF result) {
if (container == null || result == null) {
return;
}
if (srcWidth == 0 || srcHeight == 0) {
return;
}
//默认scaleType为fit center
if (scaleType == null) {
scaleType = ScaleType.FIT_CENTER;
}
result.setEmpty();
if (ScaleType.FIT_XY.equals(scaleType)) {
result.set(container);
} else if (ScaleType.CENTER.equals(scaleType)) {
Matrix matrix = matrixTake();
RectF rect = rectFTake(0, 0, srcWidth, srcHeight);
matrix.setTranslate((container.width() - srcWidth) * 0.5f, (container.height() - srcHeight) * 0.5f);
matrix.mapRect(result, rect);
rectFGiven(rect);
matrixGiven(matrix);
result.left += container.left;
result.right += container.left;
result.top += container.top;
result.bottom += container.top;
} else if (ScaleType.CENTER_CROP.equals(scaleType)) {
Matrix matrix = matrixTake();
RectF rect = rectFTake(0, 0, srcWidth, srcHeight);
float scale;
float dx = 0;
float dy = 0;
if (srcWidth * container.height() > container.width() * srcHeight) {
scale = container.height() / srcHeight;
dx = (container.width() - srcWidth * scale) * 0.5f;
} else {
scale = container.width() / srcWidth;
dy = (container.height() - srcHeight * scale) * 0.5f;
}
matrix.setScale(scale, scale);
matrix.postTranslate(dx, dy);
matrix.mapRect(result, rect);
rectFGiven(rect);
matrixGiven(matrix);
result.left += container.left;
result.right += container.left;
result.top += container.top;
result.bottom += container.top;
} else if (ScaleType.CENTER_INSIDE.equals(scaleType)) {
Matrix matrix = matrixTake();
RectF rect = rectFTake(0, 0, srcWidth, srcHeight);
float scale;
float dx;
float dy;
if (srcWidth <= container.width() && srcHeight <= container.height()) {
scale = 1f;
} else {
scale = Math.min(container.width() / srcWidth, container.height() / srcHeight);
}
dx = (container.width() - srcWidth * scale) * 0.5f;
dy = (container.height() - srcHeight * scale) * 0.5f;
matrix.setScale(scale, scale);
matrix.postTranslate(dx, dy);
matrix.mapRect(result, rect);
rectFGiven(rect);
matrixGiven(matrix);
result.left += container.left;
result.right += container.left;
result.top += container.top;
result.bottom += container.top;
} else if (ScaleType.FIT_CENTER.equals(scaleType)) {
Matrix matrix = matrixTake();
RectF rect = rectFTake(0, 0, srcWidth, srcHeight);
RectF tempSrc = rectFTake(0, 0, srcWidth, srcHeight);
RectF tempDst = rectFTake(0, 0, container.width(), container.height());
matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.CENTER);
matrix.mapRect(result, rect);
rectFGiven(tempDst);
rectFGiven(tempSrc);
rectFGiven(rect);
matrixGiven(matrix);
result.left += container.left;
result.right += container.left;
result.top += container.top;
result.bottom += container.top;
} else if (ScaleType.FIT_START.equals(scaleType)) {
Matrix matrix = matrixTake();
RectF rect = rectFTake(0, 0, srcWidth, srcHeight);
RectF tempSrc = rectFTake(0, 0, srcWidth, srcHeight);
RectF tempDst = rectFTake(0, 0, container.width(), container.height());
matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.START);
matrix.mapRect(result, rect);
rectFGiven(tempDst);
rectFGiven(tempSrc);
rectFGiven(rect);
matrixGiven(matrix);
result.left += container.left;
result.right += container.left;
result.top += container.top;
result.bottom += container.top;
} else if (ScaleType.FIT_END.equals(scaleType)) {
Matrix matrix = matrixTake();
RectF rect = rectFTake(0, 0, srcWidth, srcHeight);
RectF tempSrc = rectFTake(0, 0, srcWidth, srcHeight);
RectF tempDst = rectFTake(0, 0, container.width(), container.height());
matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.END);
matrix.mapRect(result, rect);
rectFGiven(tempDst);
rectFGiven(tempSrc);
rectFGiven(rect);
matrixGiven(matrix);
result.left += container.left;
result.right += container.left;
result.top += container.top;
result.bottom += container.top;
} else {
result.set(container);
}
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/RecycleViewDivider.java
================================================
package me.bakumon.ugank.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* RecycleView 分割线
* Created by bakumon on 2016/12/8 11:41.
*/
public class RecycleViewDivider extends RecyclerView.ItemDecoration {
private Drawable mDivider;
private int mDividerHeight = 2;//分割线高度,默认为1px
private int mOrientation;//列表的方向:LinearLayoutManager.VERTICAL或LinearLayoutManager.HORIZONTAL
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
/**
* 默认分割线:高度为2px,颜色为灰色
*
* @param context 上下文
* @param orientation 列表方向
*/
public RecycleViewDivider(Context context, int orientation) {
if (orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL) {
throw new IllegalArgumentException("请输入正确的参数!LinearLayoutManager.VERTICAL or LinearLayoutManager.HORIZONTAL");
}
mOrientation = orientation;
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
}
//获取分割线尺寸
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.set(0, 0, 0, mDividerHeight);
}
//绘制分割线
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
if (mOrientation == LinearLayoutManager.VERTICAL) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
//绘制横向 item 分割线
private void drawHorizontal(Canvas canvas, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
final int childSize = parent.getChildCount();
for (int i = 0; i < childSize; i++) {
final View child = parent.getChildAt(i);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + layoutParams.bottomMargin;
final int bottom = top + mDividerHeight;
if (mDivider != null) {
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
}
}
//绘制纵向 item 分割线
private void drawVertical(Canvas canvas, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
final int childSize = parent.getChildCount();
for (int i = 0; i < childSize; i++) {
final View child = parent.getChildAt(i);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
final int left = child.getRight() + layoutParams.rightMargin;
final int right = left + mDividerHeight;
if (mDivider != null) {
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/SquareLoading.java
================================================
package me.bakumon.ugank.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
import me.bakumon.ugank.R;
/**
* Created by growth on 11/19/16.
*/
public class SquareLoading extends ViewGroup {
private static final int DEFAULT_SQUARE_COLOR = Color.WHITE;
private static final int DEFAULT_SQUARE_SIZE = 36;
private static final int DEFAULT_SQUARE_CORNER = 8;
private static final int DEFAULT_DIVIDER_SIZE = 8;
private static final int DEFUALT_X_COUNT = 4;
private static final int DEFUALT_Y_COUNT = 3;
private static final int DEFAULT_FIRST_INDEX = DEFUALT_X_COUNT * (DEFUALT_Y_COUNT - 1);
private static final int DEFAULT_LAST_INDEX = DEFUALT_X_COUNT - 1;
private static int mSquareColor = DEFAULT_SQUARE_COLOR;
private static int mSquareSize = DEFAULT_SQUARE_SIZE;
private static int mSquareCorner = DEFAULT_SQUARE_CORNER;
private static int mDividerSize = DEFAULT_DIVIDER_SIZE;
private static int mXCount = DEFUALT_X_COUNT;
private static int mYCount = DEFUALT_Y_COUNT;
private static int mFirstIndex = DEFAULT_FIRST_INDEX;
private static int mLastIndex = DEFAULT_LAST_INDEX;
private static int mPaddingTop = 0;
private static int mPaddingLeft = 0;
private List startAnims = new ArrayList<>();
private List reverseAnims = new ArrayList<>();
private Context mContext;
public SquareLoading(Context context) {
super(context);
init(context, null);
}
public SquareLoading(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public SquareLoading(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
private void init(Context context, AttributeSet attrs) {
removeViewsIfNeeded();
mContext = context;
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SquareLoading);
mSquareColor = a.getColor(R.styleable.SquareLoading_squareColor, DEFAULT_SQUARE_COLOR);
mSquareSize = a.getDimensionPixelSize(R.styleable.SquareLoading_squareSize, DEFAULT_SQUARE_SIZE);
mSquareCorner = a.getDimensionPixelSize(R.styleable.SquareLoading_squareCorner, DEFAULT_SQUARE_CORNER);
mDividerSize = a.getDimensionPixelSize(R.styleable.SquareLoading_dividerSize, DEFAULT_DIVIDER_SIZE);
int xCount = a.getInteger(R.styleable.SquareLoading_xCount, DEFUALT_X_COUNT);
int yCount = a.getInteger(R.styleable.SquareLoading_yCount, DEFUALT_Y_COUNT);
if (xCount >= 2 && xCount <= 6) {
mXCount = xCount;
}
if (yCount >= 2 && yCount <= 6) {
mYCount = yCount;
}
a.recycle();
mFirstIndex = mXCount * (mYCount - 1);
mLastIndex = mXCount - 1;
}
// initSquare(context);
// initAnim();
}
public void setSquareColor(int color) {
mSquareColor = color;
initSquare(mContext);
initAnim();
}
private void removeViewsIfNeeded() {
if (getChildCount() > 0) {
removeAllViews();
}
}
private void initSquare(Context context) {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(mSquareColor);
gradientDrawable.setSize(mSquareSize, mSquareSize);
gradientDrawable.setCornerRadius(mSquareCorner);
for (int i = 0; i < mXCount * mYCount; i++) {
ImageView image = new ImageView(context);
image.setImageDrawable(gradientDrawable);
addView(image);
}
}
private void initAnim() {
for (int i = 0; i < getChildCount(); i++) {
RotateAnimation startAnim = new RotateAnimation(0, -90, 0, mSquareSize);
startAnim.setDuration(300);
startAnim.setFillAfter(true);
startAnim.setInterpolator(new DecelerateInterpolator());
final int finalI = i;
startAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (finalI != mLastIndex) {
int index = getNextAnimChild(true, finalI);
int delayMillis = index > mFirstIndex ? 100 : 50;
startRotateAnim(index, delayMillis);
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (finalI == mLastIndex) {
startReverseAnim(mLastIndex, 300);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
startAnims.add(startAnim);
RotateAnimation reverseAnim = new RotateAnimation(-90, 0, 0, mSquareSize);
reverseAnim.setDuration(300);
reverseAnim.setFillAfter(true);
reverseAnim.setInterpolator(new DecelerateInterpolator());
final int finalI1 = i;
reverseAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (finalI1 != mFirstIndex) {
int index = getNextAnimChild(false, finalI1);
int delayMillis = index < mXCount ? 100 : 50;
startReverseAnim(index, delayMillis);
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (finalI1 == mFirstIndex) {
startRotateAnim(mFirstIndex, 300);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
reverseAnims.add(reverseAnim);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (getChildCount() > 0) {
startRotateAnim(mFirstIndex);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
int minWidth = mSquareSize * (mXCount + 1) + (mXCount - 1) * mDividerSize;
int minHeight = mSquareSize * (mYCount + 1) + (mYCount - 1) * mDividerSize;
if (widthMode == MeasureSpec.AT_MOST || (widthMode == MeasureSpec.EXACTLY && sizeWidth < minWidth)) {
sizeWidth = minWidth;
}
if (heightMode == MeasureSpec.AT_MOST || (heightMode == MeasureSpec.EXACTLY && sizeHeight < minHeight)) {
sizeHeight = minHeight;
}
if (sizeHeight > minHeight) {
mPaddingTop = (sizeHeight - minHeight) / 2;
}
if (sizeWidth > minWidth) {
mPaddingLeft = (sizeWidth - minWidth) / 2;
}
childLayout();
setMeasuredDimension(sizeWidth, sizeHeight);
}
private void childLayout() {
int l, t, r, b;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
l = (i % mXCount + 1) * mSquareSize + (i % mXCount) * mDividerSize + mPaddingLeft;
t = (i / mXCount + 1) * mSquareSize + (i / mXCount) * mDividerSize + mPaddingTop;
r = l + mSquareSize;
b = t + mSquareSize;
child.layout(l, t, r, b);
}
}
private void startRotateAnim(final int index) {
if (startAnims != null && startAnims.size() > index) {
getChildAt(index).startAnimation(startAnims.get(index));
}
}
private void startReverseAnim(final int index) {
if (reverseAnims != null && reverseAnims.size() > index) {
getChildAt(index).startAnimation(reverseAnims.get(index));
}
}
private void startRotateAnim(final int index, int delayMillis) {
postDelayed(new Runnable() {
@Override
public void run() {
startRotateAnim(index);
}
}, delayMillis);
}
private void startReverseAnim(final int index, int delayMillis) {
postDelayed(new Runnable() {
@Override
public void run() {
startReverseAnim(index);
}
}, delayMillis);
}
private int getNextAnimChild(boolean isStart, int i) {
int index;
if (isStart) {
if (i < mXCount) {
i += mFirstIndex + 1;
return i;
}
index = i - mXCount;
} else {
if (i > mFirstIndex) {
i -= mFirstIndex + 1;
return i;
}
index = i + mXCount;
}
return index;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
cancelAnims(startAnims);
cancelAnims(reverseAnims);
}
private void cancelAnims(List anims) {
if (anims != null) {
for (RotateAnimation anim : anims) {
anim.cancel();
}
anims.clear();
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/DefaultEmptyItem.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import me.bakumon.ugank.R;
/**
* 默认的空数据视图
*
* @author cjj on 16/1/31.
*/
public class DefaultEmptyItem extends EmptyItem {
private TextView mEmptyTextView;
private ImageView mEmptyImageView;
@Override
public View onCreateView(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_with_footer_empty_layout, parent, false);
view.setLayoutParams(new ViewGroup.LayoutParams(parent.getMeasuredWidth(), parent.getMeasuredHeight()));
mEmptyTextView = (TextView) view.findViewById(R.id.rv_with_footer_empty_title);
mEmptyImageView = (ImageView) view.findViewById(R.id.rv_with_footer_empty_icon);
return view;
}
@Override
public void onBindData(View view) {
if (TextUtils.isEmpty(mEmptyText)) {
mEmptyTextView.setVisibility(View.GONE);
} else {
mEmptyTextView.setVisibility(View.VISIBLE);
mEmptyTextView.setText(mEmptyText);
}
if (mEmptyIconRes != -1) {
mEmptyImageView.setImageResource(mEmptyIconRes);
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/DefaultFootItem.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import me.bakumon.ugank.R;
/**
* @author cjj
*/
public class DefaultFootItem extends FootItem {
private ProgressBar mProgressBar;
private TextView mLoadingText;
private TextView mEndTextView;
@Override
public View onCreateView(ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.rv_with_footer_loading, parent, false);
mProgressBar = (ProgressBar) view.findViewById(R.id.rv_with_footer_loading_progress);
mEndTextView = (TextView) view.findViewById(R.id.rv_with_footer_loading_end);
mLoadingText = (TextView) view.findViewById(R.id.rv_with_footer_loading_load);
return view;
}
@Override
public void onBindData(View view, int state) {
if (state == RecyclerViewWithFooter.STATE_LOADING) {
if (TextUtils.isEmpty(loadingText)) {
showProgressBar(view.getContext().getResources().getString(R.string.rv_with_footer_loading));
} else {
showProgressBar(loadingText);
}
} else if (state == RecyclerViewWithFooter.STATE_END) {
showEnd(endText);
} else if (state == RecyclerViewWithFooter.STATE_PULL_TO_LOAD) {
// 暂时不需要
// if (TextUtils.isEmpty(pullToLoadText)) {
// showPullToLoad(view.getContext().getResources().getString(R.string.rv_with_footer_pull_load_more));
// } else {
// showPullToLoad(loadingText);
// }
}
}
public void showPullToLoad(CharSequence message) {
showEnd(message);
}
public void showProgressBar(CharSequence load) {
mEndTextView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(load)) {
mLoadingText.setVisibility(View.VISIBLE);
mLoadingText.setText(load);
} else {
mLoadingText.setVisibility(View.GONE);
}
}
public void showEnd(CharSequence end) {
mEndTextView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mLoadingText.setVisibility(View.GONE);
if (!TextUtils.isEmpty(end)) {
mEndTextView.setText(end);
}
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/EmptyItem.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
import android.view.View;
import android.view.ViewGroup;
/**
* 没数据时候的默认View
*
* @author zzz40500 on 16/1/31.
*/
public abstract class EmptyItem {
CharSequence mEmptyText;
int mEmptyIconRes = -1;
abstract View onCreateView(ViewGroup parent);
abstract void onBindData(View view);
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/FootItem.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
import android.view.View;
import android.view.ViewGroup;
/**
* Footer item
*
* @author cjj on 2016/1/30.
*/
public abstract class FootItem {
public CharSequence loadingText;
public CharSequence endText;
public CharSequence pullToLoadText;
public abstract View onCreateView(ViewGroup parent);
public abstract void onBindData(View view, int state);
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/OnLoadMoreListener.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
/**
* Load more interface
*
* @author cjj
*/
public interface OnLoadMoreListener {
void onLoadMore();
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/RecyclerViewUtils.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
/**
* 设置rv manager 类型
*
* @author cjj
*/
class RecyclerViewUtils {
private static final String TAG = "RecyclerViewUtils";
public static void setVerticalLinearLayout(RecyclerView rv) {
LinearLayoutManager layoutManager = new LinearLayoutManager(rv.getContext(), LinearLayoutManager.VERTICAL, false) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "meet an IndexOutOfBoundsException in RecyclerView");
}
}
};
rv.setLayoutManager(layoutManager);
}
public static void setGridLayout(RecyclerView rv, int spanCount) {
GridLayoutManager gridLayoutManager = new GridLayoutManager(rv.getContext(), spanCount, GridLayoutManager.VERTICAL, false) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "meet an IndexOutOfBoundsException in RecyclerView");
}
}
};
rv.setLayoutManager(gridLayoutManager);
}
public static void setStaggeredGridLayoutManager(RecyclerView rv, int spanCount) {
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e(RecyclerViewUtils.TAG, "meet an IndexOutOfBoundsException in RecyclerView");
}
}
};
rv.setLayoutManager(staggeredGridLayoutManager);
}
}
================================================
FILE: app/src/main/java/me/bakumon/ugank/widget/recyclerviewwithfooter/RecyclerViewWithFooter.java
================================================
package me.bakumon.ugank.widget.recyclerviewwithfooter;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A {@link RecyclerView} with footer which enables load more.
*
* @author cjj
*/
public class RecyclerViewWithFooter extends RecyclerView {
private static final String TAG = "RecyclerViewWithFooter";
public static final int STATE_END = 0;
public static final int STATE_LOADING = 1;
public static final int STATE_EMPTY = 2;
public static final int STATE_NONE = 3;
public static final int STATE_PULL_TO_LOAD = 4;
private boolean mIsGetDataForNet = false;
@State
private int mState = STATE_NONE;
/**
* 默认的 FootItem;
*/
private FootItem mFootItem = new DefaultFootItem();
private EmptyItem mEmptyItem = new DefaultEmptyItem();
private AdapterDataObserver mAdapterDataObserver = new AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
reset();
}
private void reset() {
mIsGetDataForNet = false;
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
super.onItemRangeChanged(positionStart, itemCount);
reset();
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
super.onItemRangeChanged(positionStart, itemCount, payload);
reset();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
reset();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
reset();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount);
reset();
}
};
public RecyclerViewWithFooter(Context context) {
super(context);
init();
}
public RecyclerViewWithFooter(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RecyclerViewWithFooter(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setVerticalLinearLayout();
}
public void setVerticalLinearLayout() {
RecyclerViewUtils.setVerticalLinearLayout(this);
}
public void setGridLayout(int span) {
RecyclerViewUtils.setGridLayout(this, span);
}
public void setStaggeredGridLayoutManager(int spanCount) {
RecyclerViewUtils.setStaggeredGridLayoutManager(this, spanCount);
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
mState = STATE_PULL_TO_LOAD;
final OnLoadMoreListenerWrapper wrapper = new OnLoadMoreListenerWrapper(onLoadMoreListener);
addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
int lastVisiblePosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
if (lastVisiblePosition >= recyclerView.getAdapter().getItemCount() - 1) {
if (mState == STATE_PULL_TO_LOAD) {
setLoading();
}
wrapper.onLoadMore();
}
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
int last[] = new int[staggeredGridLayoutManager.getSpanCount()];
staggeredGridLayoutManager.findLastVisibleItemPositions(last);
for (int aLast : last) {
Log.i(TAG, aLast + " " + recyclerView.getAdapter().getItemCount());
if (aLast >= recyclerView.getAdapter().getItemCount() - 1) {
if (mState == STATE_PULL_TO_LOAD) {
setLoading();
}
wrapper.onLoadMore();
}
}
}
}
}
});
}
@Override
public void setAdapter(Adapter adapter) {
LoadMoreAdapter loadMoreAdapter;
if (adapter instanceof LoadMoreAdapter) {
loadMoreAdapter = (LoadMoreAdapter) adapter;
loadMoreAdapter.registerAdapterDataObserver(mAdapterDataObserver);
super.setAdapter(adapter);
} else {
loadMoreAdapter = new LoadMoreAdapter(adapter);
loadMoreAdapter.registerAdapterDataObserver(mAdapterDataObserver);
super.setAdapter(loadMoreAdapter);
}
}
/**
* 设置loading提示字符串
*
* @param loadText 提示字符串
* @return {@link RecyclerViewWithFooter}
*/
public RecyclerViewWithFooter applyLoadingText(CharSequence loadText) {
mFootItem.loadingText = loadText;
return this;
}
public RecyclerViewWithFooter applyPullToLoadText(CharSequence pullToLoadText) {
mFootItem.pullToLoadText = pullToLoadText;
return this;
}
public RecyclerViewWithFooter applyEndText(CharSequence endText) {
mFootItem.endText = endText;
return this;
}
public RecyclerViewWithFooter applyEmptyText(CharSequence emptyText, @DrawableRes int drawableId) {
mEmptyItem.mEmptyIconRes = drawableId;
mEmptyItem.mEmptyText = emptyText;
return this;
}
public void setFootItem(FootItem footItem) {
if (mFootItem != null) {
if (footItem.endText == null) {
footItem.endText = mFootItem.endText;
}
if (footItem.loadingText == null) {
footItem.loadingText = mFootItem.loadingText;
}
if (footItem.pullToLoadText == null) {
footItem.pullToLoadText = mFootItem.pullToLoadText;
}
}
mFootItem = footItem;
}
public void setEmptyItem(EmptyItem emptyItem) {
if (mEmptyItem != null) {
if (emptyItem.mEmptyIconRes == -1) {
emptyItem.mEmptyIconRes = mEmptyItem.mEmptyIconRes;
}
if (emptyItem.mEmptyText == null) {
emptyItem.mEmptyText = mEmptyItem.mEmptyText;
}
}
mEmptyItem = emptyItem;
}
/**
* 切换为loading状态
*/
public void setLoading() {
if (getAdapter() != null) {
mState = STATE_LOADING;
mIsGetDataForNet = false;
getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1);
}
}
/**
* 切换为没有更多数据状态
*
* @param end 提示字符串
*/
public void setEnd(CharSequence end) {
if (getAdapter() != null) {
mIsGetDataForNet = false;
mState = STATE_END;
mFootItem.endText = end;
getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1);
}
}
/**
* 切换为没有更多数据状态
*/
public void setEnd() {
if (getAdapter() != null) {
mIsGetDataForNet = false;
mState = STATE_END;
getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1);
}
}
/**
* 切换成无数据状态
*
* @param empty 无数据状态提示消息
* @param resId 无数据状态提示图标
*/
public void setEmpty(CharSequence empty, @DrawableRes int resId) {
if (getAdapter() != null) {
mState = STATE_EMPTY;
mEmptyItem.mEmptyText = empty;
mEmptyItem.mEmptyIconRes = resId;
if (isEmpty()) {
getAdapter().notifyDataSetChanged();
}
}
}
/**
* 切换成无数据状态
*/
public void setEmpty() {
if (getAdapter() != null) {
mState = STATE_EMPTY;
if (isEmpty()) {
getAdapter().notifyDataSetChanged();
}
}
}
/**
* 数据是否为空
*/
private boolean isEmpty() {
return (mState == STATE_NONE && getAdapter().getItemCount() == 0) ||
(mState != STATE_NONE && getAdapter().getItemCount() == 1);
}
public boolean isLoadMoreEnable() {
return mState != STATE_LOADING;
}
@IntDef({STATE_END, STATE_LOADING, STATE_EMPTY, STATE_NONE, STATE_PULL_TO_LOAD})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
}
private class OnLoadMoreListenerWrapper implements OnLoadMoreListener {
private OnLoadMoreListener mOnLoadMoreListener;
public OnLoadMoreListenerWrapper(OnLoadMoreListener onLoadMoreListener) {
mOnLoadMoreListener = onLoadMoreListener;
}
@Override
public void onLoadMore() {
if (!mIsGetDataForNet && !isLoadMoreEnable()) {
mIsGetDataForNet = true;
mOnLoadMoreListener.onLoadMore();
}
}
}
public class LoadMoreAdapter extends RecyclerView.Adapter {
public static final int LOAD_MORE_VIEW_TYPE = -404;
public static final int EMPTY_VIEW_TYPE = -403;
public RecyclerView.Adapter mAdapter;
public LoadMoreAdapter(Adapter adapter) {
mAdapter = adapter;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == LOAD_MORE_VIEW_TYPE) {
return new LoadMoreVH();
} else if (viewType == EMPTY_VIEW_TYPE) {
return new EmptyVH();
}
return mAdapter.onCreateViewHolder(parent, viewType);
}
@Override
public void registerAdapterDataObserver(AdapterDataObserver observer) {
super.registerAdapterDataObserver(observer);
mAdapter.registerAdapterDataObserver(observer);
}
@Override
public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
super.unregisterAdapterDataObserver(observer);
mAdapter.unregisterAdapterDataObserver(observer);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (!isFootView(position)) {
mAdapter.onBindViewHolder(holder, position);
} else {
if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
if (layoutParams instanceof StaggeredGridLayoutManager.LayoutParams) {
((StaggeredGridLayoutManager.LayoutParams) layoutParams).setFullSpan(true);
}
} else if (getLayoutManager() instanceof GridLayoutManager) {
final GridLayoutManager layoutManager = (GridLayoutManager) getLayoutManager();
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int viewType = getAdapter().getItemViewType(position);
if (viewType < 0) {
return layoutManager.getSpanCount();
}
return 1;
}
});
}
if (holder instanceof VH) {
((VH) holder).onBindViewHolder();
}
}
}
private boolean isFootView(int position) {
return position == getItemCount() - 1 && mState != STATE_NONE;
}
@Override
public int getItemViewType(int position) {
if (!isFootView(position)) {
return mAdapter.getItemViewType(position);
} else {
if (mState == STATE_EMPTY && getItemCount() == 1) {
return EMPTY_VIEW_TYPE;
} else {
return LOAD_MORE_VIEW_TYPE;
}
}
}
@Override
public int getItemCount() {
if (mState == STATE_NONE) {
return mAdapter.getItemCount();
} else {
return mAdapter.getItemCount() + 1;
}
}
/**
* 加载更多的ViewHolder
*/
private class LoadMoreVH extends VH {
private View mItemView;
public LoadMoreVH() {
super(mFootItem.onCreateView(RecyclerViewWithFooter.this));
mItemView = itemView;
}
@Override
public void onBindViewHolder() {
super.onBindViewHolder();
if (mState == STATE_LOADING || mState == STATE_END || mState == STATE_PULL_TO_LOAD) {
mFootItem.onBindData(mItemView, mState);
}
}
}
/**
* 数据为空时的ViewHolder
*/
private class EmptyVH extends VH {
public EmptyVH() {
super(mEmptyItem.onCreateView(RecyclerViewWithFooter.this));
}
@Override
public void onBindViewHolder() {
super.onBindViewHolder();
mEmptyItem.onBindData(itemView);
}
}
class VH extends RecyclerView.ViewHolder {
public VH(View itemView) {
super(itemView);
}
public void onBindViewHolder() {
}
}
}
}
================================================
FILE: app/src/main/res/color/select_press_color_gray.xml
================================================
================================================
FILE: app/src/main/res/color/select_press_color_white.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_beauty.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_collection.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_collection_shortcut.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_edit_clear.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_favorite.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_item_author.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_item_label.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_item_time.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_loading.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_right.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_search_gank.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_search_shortcut.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_setting.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_unfavorite.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_webview_finish.xml
================================================
================================================
FILE: app/src/main/res/drawable/progressbar.xml
================================================
-
-
-
================================================
FILE: app/src/main/res/drawable/selector_history_item.xml
================================================
================================================
FILE: app/src/main/res/drawable/shape_corners_gray.xml
================================================
================================================
FILE: app/src/main/res/drawable/shape_corners_stroke_gray.xml
================================================
================================================
FILE: app/src/main/res/drawable/shape_corners_white.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_bigimg.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_favorite.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_home.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_launcher.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_search.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_setting.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_web_view.xml
================================================
================================================
FILE: app/src/main/res/layout/dialog_about.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment.xml
================================================
================================================
FILE: app/src/main/res/layout/item.xml
================================================
================================================
FILE: app/src/main/res/layout/item_favorite.xml
================================================
================================================
FILE: app/src/main/res/layout/item_history.xml
================================================
================================================
FILE: app/src/main/res/layout/item_search.xml
================================================
================================================
FILE: app/src/main/res/layout/rv_with_footer_empty_layout.xml
================================================
================================================
FILE: app/src/main/res/layout/rv_with_footer_loading.xml
================================================
================================================
FILE: app/src/main/res/menu/menu_webview.xml
================================================
================================================
FILE: app/src/main/res/values/attrs_square_loading.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#206080
#206080
#206080
#FAFAFA
#D3D3D2
#FDFDFD
#FDFDFD
#212121
#FEC006
#3E50B4
#FE5621
#9B26AF
#02A8F3
#D9DDE1
#EEEEEE
#BDBDBD
#4B4B4B
#737373
#C1C1C1
#323232
#9F9F9F
#CED0D0
#FFFFFF
#303131
================================================
FILE: app/src/main/res/values/dimens.xml
================================================
14sp
16dp
1px
================================================
FILE: app/src/main/res/values/strings.xml
================================================
有干货
搜索干货(。◕∀◕。)
搜索
分享干货
复制链接
用浏览器打开
加载中…
没有数据啦
搜索历史
清除
设置
基本设置
显示缩略图
缩略图质量
提升质量返回生效,降低质量刷新列表生效
原图
更多
关于有干货
版本:
捐赠开发者
反馈
清除缓存
收藏
> 欢迎进入 UGank]]>
搜索(不可用)
搜索
搜索
收藏(不可用)
收藏
我的收藏
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/main/res/values-v19/styles.xml
================================================
================================================
FILE: app/src/main/res/xml/shortcuts.xml
================================================
================================================
FILE: app/src/test/java/me/bakumon/ugank/ExampleUnitTest.java
================================================
package me.bakumon.ugank;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see Testing documentation
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# 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.
org.gradle.jvmargs=-Xmx1536m
# 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
ANDROID_BUILD_MIN_SDK_VERSION=15
ANDROID_BUILD_TARGET_SDK_VERSION=25
ANDROID_BUILD_SDK_VERSION=25
ANDROID_BUILD_TOOLS_VERSION=25.0.2
VERSION_NAME=2.2.3-final
VERSION_CODE=11
================================================
FILE: 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
# 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\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
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"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# 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: 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: settings.gradle
================================================
include ':app'