Repository: yiyuanliu/FlipGank
Branch: master
Commit: 80bd9062be85
Files: 124
Total size: 263.5 KB
Directory structure:
gitextract_e6p23_ug/
├── .gitignore
├── .idea/
│ ├── inspectionProfiles/
│ │ ├── Project_Default.xml
│ │ └── profiles_settings.xml
│ ├── libraries/
│ │ ├── adapter_rxjava_2_1_0.xml
│ │ ├── animated_vector_drawable_25_1_0.xml
│ │ ├── appcompat_v7_25_1_0.xml
│ │ ├── butterknife_8_4_0.xml
│ │ ├── butterknife_annotations_8_4_0.xml
│ │ ├── converter_gson_2_1_0.xml
│ │ ├── design_25_1_0.xml
│ │ ├── espresso_core_2_2_2.xml
│ │ ├── espresso_idling_resource_2_2_2.xml
│ │ ├── exposed_instrumentation_api_publish_0_5.xml
│ │ ├── glide_3_7_0.xml
│ │ ├── gson_2_7.xml
│ │ ├── hamcrest_core_1_3.xml
│ │ ├── hamcrest_integration_1_3.xml
│ │ ├── hamcrest_library_1_3.xml
│ │ ├── javawriter_2_1_1.xml
│ │ ├── javax_annotation_api_1_2.xml
│ │ ├── javax_inject_1.xml
│ │ ├── jsr305_2_0_1.xml
│ │ ├── junit_4_12.xml
│ │ ├── okhttp_3_3_0.xml
│ │ ├── okio_1_8_0.xml
│ │ ├── recyclerview_v7_25_1_0.xml
│ │ ├── retrofit_2_1_0.xml
│ │ ├── rules_0_5.xml
│ │ ├── runner_0_5.xml
│ │ ├── rxandroid_1_2_1.xml
│ │ ├── rxjava_1_2_4.xml
│ │ ├── support_annotations_25_1_0.xml
│ │ ├── support_compat_25_1_0.xml
│ │ ├── support_core_ui_25_1_0.xml
│ │ ├── support_core_utils_25_1_0.xml
│ │ ├── support_fragment_25_1_0.xml
│ │ ├── support_media_compat_25_1_0.xml
│ │ ├── support_v4_25_1_0.xml
│ │ ├── support_vector_drawable_25_1_0.xml
│ │ └── transition_25_1_0.xml
│ └── vcs.xml
├── LICENSE
├── README.md
├── app/
│ ├── .gitignore
│ ├── build.gradle
│ ├── fabric.properties
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── yiyuanliu/
│ │ └── flipgank/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── yiyuanliu/
│ │ │ └── flipgank/
│ │ │ ├── activity/
│ │ │ │ ├── BaseActivity.java
│ │ │ │ ├── CategoryActivity.java
│ │ │ │ ├── GankViewActivity.java
│ │ │ │ └── MainActivity.java
│ │ │ ├── adapter/
│ │ │ │ ├── CategoryAdapter.java
│ │ │ │ └── GankAdapter.java
│ │ │ ├── data/
│ │ │ │ ├── Api.java
│ │ │ │ ├── DataManager.java
│ │ │ │ ├── GankDbHelper.java
│ │ │ │ ├── GankItem.java
│ │ │ │ ├── GankResponse.java
│ │ │ │ └── History.java
│ │ │ ├── fragment/
│ │ │ │ ├── AboutFragment.java
│ │ │ │ ├── CategoryFragment.java
│ │ │ │ └── GankFragment.java
│ │ │ └── view/
│ │ │ ├── GankBottom.java
│ │ │ ├── GankItemView.java
│ │ │ ├── GridItemDecoration.java
│ │ │ ├── HeadItem.java
│ │ │ ├── NormalItem.java
│ │ │ └── flipview/
│ │ │ ├── FlipCard.java
│ │ │ ├── FlipLayoutManager.java
│ │ │ ├── FlipRefreshListener.java
│ │ │ └── MySnap.java
│ │ └── res/
│ │ ├── anim/
│ │ │ ├── anim_scale_in.xml
│ │ │ ├── anim_scale_out.xml
│ │ │ ├── left_in.xml
│ │ │ └── left_out.xml
│ │ ├── color/
│ │ │ └── color_icon_hint.xml
│ │ ├── drawable/
│ │ │ ├── bg_category.xml
│ │ │ ├── bg_circle.xml
│ │ │ ├── bg_info.xml
│ │ │ ├── bg_type.xml
│ │ │ ├── bt_like.xml
│ │ │ ├── bt_open.xml
│ │ │ ├── bt_show_bottom.xml
│ │ │ ├── bt_unlike.xml
│ │ │ ├── drawable_loading.xml
│ │ │ ├── drawable_placeholder.xml
│ │ │ ├── icon_about.xml
│ │ │ ├── icon_category.xml
│ │ │ ├── icon_main.xml
│ │ │ ├── shadow_bottom.xml
│ │ │ └── shadow_top.xml
│ │ ├── layout/
│ │ │ ├── activity_category.xml
│ │ │ ├── activity_gank_view.xml
│ │ │ ├── activity_main.xml
│ │ │ ├── bottom_sheet.xml
│ │ │ ├── fragment_about.xml
│ │ │ ├── fragment_category.xml
│ │ │ ├── fragment_gank.xml
│ │ │ ├── item_category.xml
│ │ │ ├── item_head.xml
│ │ │ ├── item_normal.xml
│ │ │ ├── item_tab.xml
│ │ │ ├── item_text.xml
│ │ │ ├── layout_divider_hor.xml
│ │ │ ├── layout_divider_vertical.xml
│ │ │ ├── page_first.xml
│ │ │ ├── page_loading.xml
│ │ │ └── page_normal.xml
│ │ ├── values/
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── values-v21/
│ │ │ └── styles.xml
│ │ └── values-w820dp/
│ │ └── dimens.xml
│ └── test/
│ └── java/
│ └── com/
│ └── yiyuanliu/
│ └── flipgank/
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Built application files
*.apk
*.ap_
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# Intellij
*.iml
.idea/workspace.xml
# Keystore files
*.jks
================================================
FILE: .idea/inspectionProfiles/Project_Default.xml
================================================
================================================
FILE: .idea/inspectionProfiles/profiles_settings.xml
================================================
================================================
FILE: .idea/libraries/adapter_rxjava_2_1_0.xml
================================================
================================================
FILE: .idea/libraries/animated_vector_drawable_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/appcompat_v7_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/butterknife_8_4_0.xml
================================================
================================================
FILE: .idea/libraries/butterknife_annotations_8_4_0.xml
================================================
================================================
FILE: .idea/libraries/converter_gson_2_1_0.xml
================================================
================================================
FILE: .idea/libraries/design_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/espresso_core_2_2_2.xml
================================================
================================================
FILE: .idea/libraries/espresso_idling_resource_2_2_2.xml
================================================
================================================
FILE: .idea/libraries/exposed_instrumentation_api_publish_0_5.xml
================================================
================================================
FILE: .idea/libraries/glide_3_7_0.xml
================================================
================================================
FILE: .idea/libraries/gson_2_7.xml
================================================
================================================
FILE: .idea/libraries/hamcrest_core_1_3.xml
================================================
================================================
FILE: .idea/libraries/hamcrest_integration_1_3.xml
================================================
================================================
FILE: .idea/libraries/hamcrest_library_1_3.xml
================================================
================================================
FILE: .idea/libraries/javawriter_2_1_1.xml
================================================
================================================
FILE: .idea/libraries/javax_annotation_api_1_2.xml
================================================
================================================
FILE: .idea/libraries/javax_inject_1.xml
================================================
================================================
FILE: .idea/libraries/jsr305_2_0_1.xml
================================================
================================================
FILE: .idea/libraries/junit_4_12.xml
================================================
================================================
FILE: .idea/libraries/okhttp_3_3_0.xml
================================================
================================================
FILE: .idea/libraries/okio_1_8_0.xml
================================================
================================================
FILE: .idea/libraries/recyclerview_v7_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/retrofit_2_1_0.xml
================================================
================================================
FILE: .idea/libraries/rules_0_5.xml
================================================
================================================
FILE: .idea/libraries/runner_0_5.xml
================================================
================================================
FILE: .idea/libraries/rxandroid_1_2_1.xml
================================================
================================================
FILE: .idea/libraries/rxjava_1_2_4.xml
================================================
================================================
FILE: .idea/libraries/support_annotations_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_compat_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_core_ui_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_core_utils_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_fragment_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_media_compat_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_v4_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/support_vector_drawable_25_1_0.xml
================================================
================================================
FILE: .idea/libraries/transition_25_1_0.xml
================================================
================================================
FILE: .idea/vcs.xml
================================================
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly savedState otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# FlipGank
[download apk](https://github.com/yiyuanliu/FlipGank/releases)
一款 FlipBoard 翻页风格的 Gank.io 客户端,使用 RecyclerView 实现。
## Todo
- 使用 Rxjava 2.0
- 添加图片下载
- Readability
## 数据来源
[Gank.io](http://gank.io)
## 第三方类库
- [Glide](https://github.com/bumptech/glide)
- [Okhttp](http://square.github.io/okhttp/)
- [RxJava](https://github.com/ReactiveX/RxJava)
- [Retrofit](https://square.github.io/retrofit/)
- [Butterknife](http://jakewharton.github.io/butterknife/)
## About me
A student in Uestc. Android developer.
Email: yiyuanliu1997@gmail.com
## 开源协议
```
Copyright YiyuanLiu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle
================================================
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.yiyuanliu.flipgank"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:recyclerview-v7:25.1.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'io.reactivex:rxjava:1.2.4'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.android.support:design:25.1.0'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.android.support:support-v4:25.1.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
testCompile 'junit:junit:4.12'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}
================================================
FILE: app/fabric.properties
================================================
#Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public.
#Wed Dec 28 20:37:19 CST 2016
apiSecret=ddbd08ed569cbe7180a1c8cb1624f71a7193bd3285b3eb1c038951d23e317628
================================================
FILE: app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\work\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 *;
#}
================================================
FILE: app/src/androidTest/java/com/yiyuanliu/flipgank/ExampleInstrumentedTest.java
================================================
package com.yiyuanliu.flipgank;
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("com.yiyuanliu.flipgank", appContext.getPackageName());
}
}
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/activity/BaseActivity.java
================================================
package com.yiyuanliu.flipgank.activity;
import android.support.v7.app.AppCompatActivity;
/**
* Created by YiyuanLiu on 2016/12/22.
*/
public abstract class BaseActivity extends AppCompatActivity {
public abstract void showInfo(String info);
public abstract void setLoading(boolean isLoading);
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/activity/CategoryActivity.java
================================================
package com.yiyuanliu.flipgank.activity;
import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.fragment.GankFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class CategoryActivity extends BaseActivity {
private static final String TAG = "CategoryActivity";
private static final String ARG_TYPE = "type";
public static void startActivity(Context context, String type) {
Intent intent = new Intent(context, CategoryActivity.class);
intent.putExtra(ARG_TYPE, type);
context.startActivity(intent);
}
@BindView(R.id.title)
TextView title;
@BindView(R.id.scrim)
View scrim;
@BindView(R.id.loading)
ProgressBar loading;
@BindView(R.id.text)
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
ButterKnife.bind(this);
if (savedInstanceState == null) {
if (getIntent() == null) {
throw new IllegalStateException();
}
String type = getIntent().getExtras().getString(ARG_TYPE);
title.setText(type);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, GankFragment.newInstance(type))
.commit();
}
}
public void setLoading(boolean isLoading) {
Log.d(TAG, "setLoading: " + isLoading);
scrim.removeCallbacks(hideInfo);
scrim.animate().cancel();
scrim.animate().setListener(null);
if (isLoading) {
scrim.setVisibility(View.VISIBLE);
loading.setVisibility(View.VISIBLE);
text.setText("加载中...");
scrim.setAlpha(0f);
scrim.animate().alpha(1f).start();
} else {
scrim.animate().alpha(0f).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
scrim.setVisibility(View.INVISIBLE);
}
@Override public void onAnimationStart(Animator animation) { }
@Override public void onAnimationCancel(Animator animation) { }
@Override public void onAnimationRepeat(Animator animation) { }
}).start();
}
}
public void showInfo(String info) {
Log.d(TAG, "showInfo: " + info);
scrim.animate().cancel();
scrim.removeCallbacks(hideInfo);
scrim.animate().setListener(null);
scrim.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
text.setText(info);
scrim.setAlpha(0f);
scrim.animate().alpha(1f).setDuration(230).start();
scrim.postDelayed(hideInfo, 800);
}
private Runnable hideInfo = new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: hideInfo");
scrim.animate().cancel();
scrim.animate().alpha(0f).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
scrim.setVisibility(View.INVISIBLE);
}
@Override public void onAnimationStart(Animator animation) { }
@Override public void onAnimationCancel(Animator animation) { }
@Override public void onAnimationRepeat(Animator animation) { }
}).start();
}
};
@OnClick(R.id.back)
void back() {
finish();
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/activity/GankViewActivity.java
================================================
package com.yiyuanliu.flipgank.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.adapter.GankAdapter;
import com.yiyuanliu.flipgank.data.GankItem;
import com.yiyuanliu.flipgank.view.GankBottom;
import com.yiyuanliu.flipgank.view.GankItemView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class GankViewActivity extends BaseActivity {
private static final String ARG_GANK = "gank";
public static void startActivity(Context context, GankItem gankItem) {
Intent intent = new Intent(context, GankViewActivity.class);
intent.putExtra(ARG_GANK, gankItem);
context.startActivity(intent);
}
@BindView(R.id.webview)
WebView mWebView;
@BindView(R.id.like)
ImageButton likeButton;
@BindView(R.id.loading)
ProgressBar loading;
GankItem mGankItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gank_view);
ButterKnife.bind(this);
if (getIntent() == null) {
throw new IllegalStateException();
}
mGankItem = (GankItem) getIntent().getExtras().getSerializable(ARG_GANK);
mWebView.loadUrl(mGankItem.url);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setLoading(true);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setLoading(false);
}
});
if (mGankItem.like) {
likeButton.setImageResource(R.drawable.bt_like);
} else {
likeButton.setImageResource(R.drawable.bt_unlike);
}
}
@Override
protected void onDestroy() {
mWebView.destroy();
super.onDestroy();
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
@OnClick(R.id.back)
void close(View view) {
finish();
}
@OnClick(R.id.share)
void share(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mGankItem.desc + "\n" + mGankItem.url);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "分享链接"));
}
@OnClick(R.id.open_in_browser)
void open(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mGankItem.url));
startActivity(intent);
}
@OnClick(R.id.like)
void like(View view) {
mGankItem.like = !mGankItem.like;
if (mGankItem.like) {
likeButton.setImageResource(R.drawable.bt_like);
} else {
likeButton.setImageResource(R.drawable.bt_unlike);
}
}
@OnClick(R.id.more)
void showMore(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
GankBottom gankBottom = (GankBottom) LayoutInflater.from(this).inflate(R.layout.bottom_sheet, null, false);
gankBottom.bind(mGankItem, null);
bottomSheetDialog.setContentView( gankBottom);
bottomSheetDialog.show();
}
@Override
public void showInfo(String info) { }
@Override
public void setLoading(boolean isLoading) {
loading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/activity/MainActivity.java
================================================
package com.yiyuanliu.flipgank.activity;
import android.animation.Animator;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.adapter.CategoryAdapter;
import com.yiyuanliu.flipgank.data.GankItem;
import com.yiyuanliu.flipgank.fragment.AboutFragment;
import com.yiyuanliu.flipgank.fragment.CategoryFragment;
import com.yiyuanliu.flipgank.fragment.GankFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends BaseActivity {
private static final String TAG = "MainActivity";
@BindView(R.id.scrim)
View scrim;
@BindView(R.id.loading)
ProgressBar loading;
@BindView(R.id.text)
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(mPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_main);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_category);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_about);
}
private PagerAdapter mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
if (position == 1) {
return CategoryFragment.newInstance();
} else if (position == 2) {
return AboutFragment.newInstance();
}
return GankFragment.newInstance(null);
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
};
public void setLoading(boolean isLoading) {
Log.d(TAG, "setLoading: " + isLoading);
scrim.removeCallbacks(hideInfo);
scrim.animate().cancel();
scrim.animate().setListener(null);
if (isLoading) {
scrim.setVisibility(View.VISIBLE);
loading.setVisibility(View.VISIBLE);
text.setText("加载中...");
scrim.setAlpha(0f);
scrim.animate().alpha(1f).start();
} else {
scrim.animate().alpha(0f).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
scrim.setVisibility(View.INVISIBLE);
}
@Override public void onAnimationStart(Animator animation) { }
@Override public void onAnimationCancel(Animator animation) { }
@Override public void onAnimationRepeat(Animator animation) { }
}).start();
}
}
public void showInfo(String info) {
Log.d(TAG, "showInfo: " + info);
scrim.animate().cancel();
scrim.removeCallbacks(hideInfo);
scrim.animate().setListener(null);
scrim.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
text.setText(info);
scrim.setAlpha(1f);
scrim.postDelayed(hideInfo, 800);
}
private Runnable hideInfo = new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: hideInfo");
scrim.animate().cancel();
scrim.animate().alpha(0f).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
scrim.setVisibility(View.INVISIBLE);
}
@Override public void onAnimationStart(Animator animation) { }
@Override public void onAnimationCancel(Animator animation) { }
@Override public void onAnimationRepeat(Animator animation) { }
}).start();
}
};
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/adapter/CategoryAdapter.java
================================================
package com.yiyuanliu.flipgank.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.activity.CategoryActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by YiyuanLiu on 2016/12/21.
*/
public class CategoryAdapter extends RecyclerView.Adapter {
private List mCategoryList;
public CategoryAdapter() {
mCategoryList = new ArrayList<>();
mCategoryList.add("Android");
mCategoryList.add("iOS");
mCategoryList.add("App");
mCategoryList.add("拓展资源");
mCategoryList.add("瞎推荐");
mCategoryList.add("前端");
mCategoryList.add("休息视频");
Collections.sort(mCategoryList);
}
public void addCategory(List categoryList) {
for (String category: categoryList) {
if (category.equals("福利")) {
continue;
}
boolean has = false;
for (String item: mCategoryList) {
if (category.equals(item)){
has = true;
break;
}
}
if (!has) {
mCategoryList.add(category);
}
}
Collections.sort(mCategoryList);
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
return new CategoryVh(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((CategoryVh)holder).bind(mCategoryList.get(position));
}
@Override
public int getItemCount() {
return mCategoryList.size();
}
class CategoryVh extends RecyclerView.ViewHolder {
@BindView(R.id.category)
TextView textView;
@BindView(R.id.image)
ImageView imageView;
String category;
public CategoryVh(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(String category) {
this.category = category;
this.textView.setText(category);
if (getResId(category) != 0) {
Glide.with(itemView.getContext())
.load(getResId(category))
.into(imageView);
}
}
@OnClick(R.id.click)
void onClick() {
CategoryActivity.startActivity(itemView.getContext(), category);
}
}
private static final int getResId(String category) {
switch (category) {
case "Android": return R.drawable.android;
case "iOS": return R.drawable.ios;
case "App": return R.drawable.app;
case "休息视频": return R.drawable.rest;
case "拓展资源": return R.drawable.more;
case "前端": return R.drawable.javascript;
case "瞎推荐": return R.drawable.recommend;
default: return 0;
}
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/adapter/GankAdapter.java
================================================
package com.yiyuanliu.flipgank.adapter;
import android.content.Context;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.activity.GankViewActivity;
import com.yiyuanliu.flipgank.data.DataManager;
import com.yiyuanliu.flipgank.data.GankItem;
import com.yiyuanliu.flipgank.view.GankItemView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
/**
* Created by YiyuanLiu on 2016/12/17.
*/
public class GankAdapter extends RecyclerView.Adapter implements GankItemView.Listener {
private static final String TAG = "GankAdapter";
private List pageList = new ArrayList<>();
private List gankItems = new ArrayList<>();
private Listener mListener;
private Context mContext;
private boolean mHasMore = true;
public GankAdapter(Context context,Listener listener) {
mListener = listener;
mContext = context;
}
public void setHasMore(boolean hasMore) {
if (mHasMore == hasMore) {
return;
}
mHasMore = hasMore;
notifyItemChanged(getItemCount() - 1);
}
public void clear() {
int size = pageList.size();
pageList.clear();
gankItems.clear();
notifyItemRangeRemoved(0, size);
}
public void addData(List gankItemList) {
gankItemList.addAll(gankItems);
gankItems.clear();
FirstPage bigImagePage = FirstPage.gen(gankItemList);
if (bigImagePage != null) {
pageList.add(bigImagePage);
notifyItemInserted(pageList.size() - 1);
}
while (gankItemList.size() / 4 != 0) {
NormalPage normal = NormalPage.gen(gankItemList);
pageList.add(normal);
notifyItemInserted(pageList.size() - 1);
}
if (gankItemList.size() != 0) {
gankItems.addAll(gankItemList);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, "create view holder " + viewType);
if (viewType == Page.TYPE_BIG_IMAGE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.page_first, parent, false);
return new FirstPageVh(view);
}
if (viewType == Page.TYPE_NORMAL) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.page_normal, parent, false);
return new NormalVh(view);
}
if (viewType == 0) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.page_loading, parent, false);
return new LoadingVh(view);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int type = getItemViewType(position);
if (type == Page.TYPE_BIG_IMAGE) {
FirstPageVh imageVh = (FirstPageVh) holder;
imageVh.bind(pageList.get(position));
}
if (type == Page.TYPE_NORMAL) {
NormalVh normalVh = (NormalVh) holder;
normalVh.bind(pageList.get(position));
}
if (type == 0) {
LoadingVh loadingVh = (LoadingVh) holder;
((LoadingVh) holder).bind(mHasMore);
}
}
@Override
public int getItemViewType(int position) {
if (position < pageList.size()) {
return pageList.get(position).getType();
} else {
return 0;
}
}
@Override
public int getItemCount() {
return pageList.size() + 1;
}
public int getDataCount() {
return pageList.size();
}
@Override
public void open(GankItem gankItem) {
GankViewActivity.startActivity(mContext, gankItem);
}
@Override
public void showBottomSheet(GankItem gankItem) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(mContext);
GankItemView gankItemView = (GankItemView) LayoutInflater.from(mContext).inflate(R.layout.bottom_sheet, null, false);
gankItemView.bind(gankItem, GankAdapter.this);
bottomSheetDialog.setContentView((View) gankItemView);
bottomSheetDialog.show();
}
@Override
public void like(GankItem gankItem) {
if (gankItem.like) {
mListener.showInfo("已喜欢");
} else {
mListener.showInfo("取消喜欢");
}
DataManager.getInstance(mContext).updateLike(gankItem);
}
class LoadingVh extends RecyclerView.ViewHolder {
@BindView(R.id.loading)
ProgressBar loading;
@BindView(R.id.text)
TextView textView;
LoadingVh(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
void bind(boolean hasMore) {
if (hasMore) {
loading.setVisibility(View.VISIBLE);
textView.setText("加载中...");
} else {
loading.setVisibility(View.GONE);
textView.setText("没有更多内容");
}
}
}
class FirstPageVh extends RecyclerView.ViewHolder {
@BindViews({R.id.item_head, R.id.item1})
GankItemView[] items;
FirstPageVh(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
void bind(Page page) {
for (int i = 0;i < page.getSize() && i < items.length;i ++) {
items[i].bind(page.items[i], GankAdapter.this);
}
}
}
class NormalVh extends RecyclerView.ViewHolder {
@BindViews({R.id.item1, R.id.item2, R.id.item3, R.id.item4})
GankItemView items[];
NormalVh(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
void bind(Page page) {
for (int i = 0;i < page.getSize() && i < items.length;i ++) {
items[i].bind(page.items[i], GankAdapter.this);
}
}
}
private abstract static class Page {
static final int TYPE_BIG_IMAGE = 1;
static final int TYPE_NORMAL = 2;
GankItem[] items;
abstract int getType();
abstract int getSize();
}
/**
* 通常为某天信息的第一页
* 样式为上方一个大图片,下方一个内容
*
*/
private static class FirstPage extends Page {
static FirstPage gen(List gankItemList) {
GankItem imageItem = null;
if (gankItemList == null || gankItemList.size() <= 1) {
return null;
}
Iterator gankItemIterator = gankItemList.iterator();
while (gankItemIterator.hasNext()) {
GankItem item = gankItemIterator.next();
if (item.type.equals("福利")) {
imageItem = item;
gankItemIterator.remove();
break;
}
}
if (imageItem == null) {
return null;
}
int count = 2;
int i = 1;
GankItem[] items = new GankItem[count];
items[0] = imageItem;
gankItemIterator = gankItemList.iterator();
while (gankItemIterator.hasNext() && count > i) {
GankItem item = gankItemIterator.next();
items[i] = item;
i ++;
gankItemIterator.remove();
}
FirstPage bigImagePage = new FirstPage();
bigImagePage.items = items;
return bigImagePage;
}
@Override int getSize() {
return items == null ? 0 : items.length;
}
@Override int getType() {
return TYPE_BIG_IMAGE;
}
}
/**
* 这是通常形式的 page
* 样式为四个内容竖直排列
*/
private static class NormalPage extends Page {
static NormalPage gen(List gankItemList) {
if (gankItemList == null || gankItemList.isEmpty()) {
return null;
}
int size = gankItemList.size() > 4 ? 4 : gankItemList.size();
GankItem[] items = new GankItem[size];
gankItemList.subList(0, size).toArray(items);
gankItemList.removeAll(Arrays.asList(items));
NormalPage normalPage = new NormalPage();
normalPage.items = items;
return normalPage;
}
int getSize() {
return items == null ? 0 : items.length;
}
@Override
int getType() {
return TYPE_NORMAL;
}
}
public interface Listener {
void showInfo(String info);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/data/Api.java
================================================
package com.yiyuanliu.flipgank.data;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
/**
* Created by YiyuanLiu on 2016/12/15.
*/
public interface Api {
String BASE_URL = "http://gank.io/";
@GET("api/day/{year}/{month}/{day}")
Observable loadData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/data/DataManager.java
================================================
package com.yiyuanliu.flipgank.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
/**
* Created by YiyuanLiu on 2016/12/16.
*/
public class DataManager {
private static final String TAG = "DataManager";
private static volatile DataManager sInstance;
public static DataManager getInstance(Context context) {
if (sInstance == null) {
synchronized (DataManager.class) {
if (sInstance == null) {
sInstance = new DataManager(context);
}
}
}
return sInstance;
}
private DataManager(Context context) {
Context context1 = context.getApplicationContext();
GankDbHelper gankDbHelper = new GankDbHelper(context1);
sqLiteDatabase = gankDbHelper.getWritableDatabase();
}
private SQLiteDatabase sqLiteDatabase;
private Api api;
public Observable> loadCategory() {
return Observable.create(new Observable.OnSubscribe>() {
@Override
public void call(Subscriber super List> subscriber) {
Cursor cursor = sqLiteDatabase.query(GankDbHelper.Contract.TABLE_CATEGORY, null, null, null, null, null, null);
boolean hasMore = cursor.moveToFirst();
List categorys = new ArrayList<>();
while (hasMore) {
int categoryPos = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_CATEGORY);
String category = cursor.getString(categoryPos);
categorys.add(category);
hasMore = cursor.moveToNext();
}
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(categorys);
}
cursor.close();
}
});
}
/**
* 从当前时间加载数据
* 调用者应通过返回数据中的时间判断是否有更新的内容
*
* @return Observable
*/
public Observable> loadNew() {
return loadFromDay(getToday());
}
/**
* 加载更多内容
* 在分页时 loadMore 从上次加载到的位置继续
* 第一次调用从数据库缓存中最新时间开始加载
* 如果返回的数据为空,意味着已经没有更多内容
*
* @param lastLoaded 上次加载到的日期,用于分页加载
* @return Observable
*/
public Observable> loadMore(String lastLoaded) {
String day;
if (lastLoaded == null) {
History history = getLatestUpdate(true);
if (history == null) {
day = getToday();
} else {
day = history.day;
}
} else {
// 日期向前一天
day = dayBack(lastLoaded);
}
return loadFromDay(day);
}
/**
* 从 day 开始进行加载任务,发现新的内容后停止
* 如果没有内容,加载前一天的内容,如果返回的数据为空,意味着日期以前已经没有更多内容
*
* @param day 加载日期
*/
private Observable> loadFromDay(final String day) {
Log.d(TAG, "loadFromDay: " + day);
if (isOver(day)) {
List emptyList = new ArrayList<>();
return Observable.just(emptyList);
} else return load(day).flatMap(new Func1, Observable>>() {
@Override
public Observable> call(List gankItemList) {
// 检查是否获得了数据
if (gankItemList.size() == 0) {
String dayBack = dayBack(day);
return loadFromDay(dayBack);
} else {
return Observable.just(gankItemList);
}
}
});
}
/**
* 加载某一天的数据,首先检查数据库,否则从网络中加载并更新数据库
*
* @param dayStr 日期
* @return Observable
*/
private Observable> load(final String dayStr) {
Log.d(TAG, "load: " + dayStr);
History history = checkLoadHistory(dayStr);
if (history == null) {
return loadFromGank(dayStr).map(new Func1, List>() {
@Override
public List call(List gankItemList) {
updateDb(gankItemList, dayStr);
return gankItemList;
}
});
} else {
return loadFormDb(dayStr);
}
}
/**
* 从 gank.io 加载某一天的内容
* @param dayStr 日期
* @return 返回加载到的内容
*/
private Observable> loadFromGank(final String dayStr) {
Log.d(TAG, "loadFromGank: " + dayStr);
String[] parts = dayStr.split("/");
int year = Integer.valueOf(parts[0]);
int month = Integer.valueOf(parts[1]);
int day = Integer.valueOf(parts[2]);
if (api == null) {
Retrofit.Builder builder = new Retrofit.Builder();
api = builder.baseUrl(Api.BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build().create(Api.class);
}
return api.loadData(year, month, day)
.map(new Func1>() {
@Override
public List call(GankResponse gankResponse) {
if (gankResponse.error) {
throw new RuntimeException("gank error");
}
List gankItemList = new ArrayList<>();
if (gankResponse.hasData()) {
for (Map.Entry> entry: gankResponse.results.entrySet()) {
gankItemList.addAll(entry.getValue());
}
}
for (GankItem gankItem: gankItemList) {
gankItem.day = dayStr;
}
return gankItemList;
}
});
}
public void updateLike(GankItem gankItem) {
ContentValues item = new ContentValues();
item.put(GankDbHelper.Contract.COLUMN_ID, gankItem.id);
item.put(GankDbHelper.Contract.COLUMN_CATEGORY, gankItem.type);
item.put(GankDbHelper.Contract.COLUMN_DEST, gankItem.desc);
item.put(GankDbHelper.Contract.COLUMN_DAY, gankItem.day);
item.put(GankDbHelper.Contract.COLUMN_URL, gankItem.url);
item.put(GankDbHelper.Contract.COLUMN_WHO, gankItem.who);
item.put(GankDbHelper.Contract.COLUMN_LIKE, gankItem.like ? 1 : 0);
item.put(GankDbHelper.Contract.COLUMN_IMAGE, gankItem.getImage());
sqLiteDatabase.update(GankDbHelper.Contract.TABLE_DATA, item,
GankDbHelper.Contract.COLUMN_ID + "=?", new String[]{ gankItem.id });
}
/**
* 从 dataBase 中加载某天的内容
* @param day 日期
* @return 内容
*/
private Observable> loadFormDb(final String day) {
Log.d(TAG, "loadFormDb: " + day);
return Observable.create(new Observable.OnSubscribe>() {
@Override
public void call(Subscriber super List> subscriber) {
Log.d(TAG, "call: " + day);
final List gankItemList = new ArrayList<>();
Cursor cursor = sqLiteDatabase.query(GankDbHelper.Contract.TABLE_DATA, null,
GankDbHelper.Contract.COLUMN_DAY + " = ?", new String[]{day},
null, null, null);
boolean hasMore = cursor.moveToFirst();
while (hasMore) {
GankItem gankItem = new GankItem();
int columnDesc = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_DEST);
int columnUrl = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_URL);
int columnWho = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_WHO);
int columnType = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_CATEGORY);
int columnDay = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_DAY);
int columnImage = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_IMAGE);
int columnLike = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_LIKE);
int columnId = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_ID);
gankItem.desc = cursor.getString(columnDesc);
gankItem.url = cursor.getString(columnUrl);
gankItem.who = cursor.getString(columnWho);
gankItem.type = cursor.getString(columnType);
gankItem.day = cursor.getString(columnDay);
gankItem.image = cursor.getString(columnImage);
gankItem.like = cursor.getInt(columnLike) != 0;
gankItem.id = cursor.getString(columnId);
gankItemList.add(gankItem);
hasMore = cursor.moveToNext();
}
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(gankItemList);
subscriber.onCompleted();
}
cursor.close();
Log.d(TAG, "call: end " + day);
}
});
}
/**
* 最近一次的更新时间
* @return 最近更新,日期形式 2016/12/16
*/
private History getLatestUpdate(boolean shouldHasData) {
History ans = null;
int ansInt = Integer.MIN_VALUE;
Cursor cursor = sqLiteDatabase.query(GankDbHelper.Contract.TABLE_LOAD_HISTORY,
null, null, null, null, null, null);
boolean hasMore = cursor.moveToFirst();
while (hasMore) {
int columnDay = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_DAY);
int columnHasData = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_HAS_DATA);
String day = cursor.getString(columnDay);
boolean hasData = cursor.getInt(columnHasData) == 1;
int dayInt = Integer.valueOf(day.replaceAll("/", ""));
if (dayInt > ansInt && (hasData || !shouldHasData)) {
if (ans == null) {
ans = new History();
}
ans.day = day;
ans.hasData = hasData;
ansInt = dayInt;
}
hasMore = cursor.moveToNext();
}
cursor.close();
return ans;
}
private void updateDb(List gankItemList, String day) {
final boolean isToday = isToday(day);
if (gankItemList.size() == 0) {
// 返回的列表中没有消息
if (isToday) {
// do nothing, 可能代码家还没干活,等等再说
} else {
// 那就是说今天没东西了
updateLoadHistory(day, false);
}
} else {
sqLiteDatabase.beginTransaction();
updateLoadHistory(day, true);
updateDataDb(gankItemList, day);
updateCategory(gankItemList);
sqLiteDatabase.setTransactionSuccessful();
sqLiteDatabase.endTransaction();
}
}
private void updateDataDb(List gankItemList, String day) {
if (gankItemList == null || gankItemList.size() == 0) {
Log.d(TAG, "updateDataDb return for no data");
return;
}
for (GankItem gankItem: gankItemList) {
ContentValues item = new ContentValues();
item.put(GankDbHelper.Contract.COLUMN_ID, gankItem.id);
item.put(GankDbHelper.Contract.COLUMN_CATEGORY, gankItem.type);
item.put(GankDbHelper.Contract.COLUMN_DEST, gankItem.desc);
item.put(GankDbHelper.Contract.COLUMN_DAY, day);
item.put(GankDbHelper.Contract.COLUMN_URL, gankItem.url);
item.put(GankDbHelper.Contract.COLUMN_WHO, gankItem.who);
item.put(GankDbHelper.Contract.COLUMN_IMAGE, gankItem.getImage());
item.put(GankDbHelper.Contract.COLUMN_LIKE, gankItem.like ? 1 : 0);
sqLiteDatabase.insert(GankDbHelper.Contract.TABLE_DATA, null, item);
}
}
/**
* 更新 category 列表
* @param gankItemList 输入数据
*/
private void updateCategory(List gankItemList) {
if (gankItemList == null || gankItemList.size() == 0) {
return;
}
Set category = new HashSet<>();
for (GankItem gankItem: gankItemList) {
category.add(gankItem.type);
}
for (String item: category) {
Cursor cursor = sqLiteDatabase.query(GankDbHelper.Contract.TABLE_CATEGORY, null,
GankDbHelper.Contract.COLUMN_CATEGORY + "=?", new String[]{item}, null, null, null );
if (!cursor.moveToFirst()) {
ContentValues contentValues = new ContentValues();
contentValues.put(GankDbHelper.Contract.COLUMN_CATEGORY, item);
sqLiteDatabase.insert(GankDbHelper.Contract.TABLE_CATEGORY, null, contentValues);
}
cursor.close();
}
}
/**
* 将日期添加到 load_history 表之中,表示当天的消息已经加载过了
* @param day 日期
*/
private void updateLoadHistory(String day, boolean hasData) {
ContentValues contentValues = new ContentValues();
contentValues.put(GankDbHelper.Contract.COLUMN_DAY, day);
contentValues.put(GankDbHelper.Contract.COLUMN_HAS_DATA, hasData ? 1 : 0);
sqLiteDatabase.insert(GankDbHelper.Contract.TABLE_LOAD_HISTORY, null, contentValues);
}
/**
* 检查当天是否被加载过
* @param day 所需查询的日期
* @return 是否已经加载, null 表示未加载,反之表示加载情况
*/
private History checkLoadHistory(String day) {
Cursor cursor = sqLiteDatabase.query(GankDbHelper.Contract.TABLE_LOAD_HISTORY, null,
GankDbHelper.Contract.COLUMN_DAY + " = ?", new String[]{day},
null, null, null);
if (cursor.moveToFirst()) {
History history = new History();
int columnDay = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_DAY);
int columnHasData = cursor.getColumnIndex(GankDbHelper.Contract.COLUMN_HAS_DATA);
history.day = cursor.getString(columnDay);
history.hasData = cursor.getInt(columnHasData) == 1;
cursor.close();
return history;
} else {
cursor.close();
return null;
}
}
private static boolean isToday(String dayStr) {
int[] dayInt = dayStr2Int(dayStr);
return isToday(dayInt[0], dayInt[1], dayInt[2]);
}
private static boolean isToday(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
int yearToday = calendar.get(Calendar.YEAR);
int monthToday = calendar.get(Calendar.MONTH) + 1;
int dayToday = calendar.get(Calendar.DAY_OF_MONTH);
return year == yearToday && monthToday == month && dayToday == day;
}
private static int[] dayStr2Int(String dayStr) {
String[] parts = dayStr.split("/");
int year = Integer.valueOf(parts[0]);
int month = Integer.valueOf(parts[1]);
int day = Integer.valueOf(parts[2]);
return new int[]{year, month, day};
}
private static String dayInt2Str(int year, int month, int day) {
return year + "/" + month + "/" + day;
}
private static final long A_DAY = 24 * 60 * 60 * 1000;
/**
* 获取前一天的日期字符串, 例如输入 2016/12/16
* @return 前一天的时间 2016/12/15
*/
private static String dayBack(String dayStr) {
int[] dayInts = dayStr2Int(dayStr);
Calendar calendar = Calendar.getInstance();
calendar.set(dayInts[0], dayInts[1] - 1, dayInts[2]);
Date date = calendar.getTime();
long time = date.getTime() - A_DAY;
date.setTime(time);
calendar.setTime(date);
return dayInt2Str(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
}
private static String dayNext(String dayStr) {
int[] dayInts = dayStr2Int(dayStr);
Calendar calendar = Calendar.getInstance();
calendar.set(dayInts[0], dayInts[1] - 1, dayInts[2]);
Date date = calendar.getTime();
long time = date.getTime() + A_DAY;
date.setTime(time);
calendar.setTime(date);
return dayInt2Str(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
}
private static String getToday() {
Calendar calendar = Calendar.getInstance();
return dayInt2Str(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
}
/**
* gank.io 最早的时间应该是 2015/05/18,
* @param dayStr 日期
* @return 是否超过了 gank 的初始时间
*/
private static boolean isOver(String dayStr) {
int[] day = dayStr2Int(dayStr);
Calendar gankStart = Calendar.getInstance();
gankStart.set(2015, 4, 18);
Calendar checkTime = Calendar.getInstance();
checkTime.set(day[0], day[1] - 1, day[2]);
return checkTime.before(gankStart);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/data/GankDbHelper.java
================================================
package com.yiyuanliu.flipgank.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by YiyuanLiu on 2016/12/15.
*/
public class GankDbHelper extends SQLiteOpenHelper {
public static class Contract {
public static final String DB_NAME = "gank";
public static final String TABLE_DATA = "data";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DEST = "desc";
public static final String COLUMN_URL = "url";
public static final String COLUMN_WHO = "who";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_IMAGE = "image";
public static final String COLUMN_CATEGORY = "category_name";
public static final String COLUMN_LIKE = "like";
public static final String CREATE_TABLE_DATA = "CREATE TABLE " + TABLE_DATA + " ( "
+ COLUMN_ID + " TEXT PRIMARY KEY, "
+ COLUMN_DEST + " TEXT, "
+ COLUMN_URL + " TEXT, "
+ COLUMN_CATEGORY + " TEXT, "
+ COLUMN_WHO + " TEXT, "
+ COLUMN_IMAGE + " TEXT, "
+ COLUMN_LIKE + " INTEGER, "
+ COLUMN_DAY + " TEXT " + " )";
public static final String TABLE_CATEGORY = "category";
public static final String CREATE_TABLE_CATEGORY = "CREATE TABLE " + TABLE_CATEGORY + " ( "
+ COLUMN_CATEGORY + " TEXT PRIMARY KEY" + " )";
public static final String TABLE_LOAD_HISTORY = "load_history";
public static final String COLUMN_HAS_DATA = "has_data";
public static final String CREATE_TABLE_HISTORY = "CREATE TABLE " + TABLE_LOAD_HISTORY + " ( "
+ COLUMN_DAY + " TEXT PRIMARY KEY, "
+ COLUMN_HAS_DATA + " INTEGER " + " )";
}
public GankDbHelper(Context context) {
super(context, Contract.DB_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Contract.CREATE_TABLE_DATA);
db.execSQL(Contract.CREATE_TABLE_CATEGORY);
db.execSQL(Contract.CREATE_TABLE_HISTORY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/data/GankItem.java
================================================
package com.yiyuanliu.flipgank.data;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
* Created by YiyuanLiu on 2016/12/15.
*/
public class GankItem implements Serializable {
@SerializedName("_id")
public String id;
public String createAt;
public String desc;
public String publishedAt;
public String type;
public String url;
public String who;
public String day;
public List images;
public String image;
public boolean like;
public String getImage() {
if (image != null) {
return image;
} else if (!type.equals("福利")){
return images == null || images.size() == 0 ? null : images.get(0);
} else {
return url;
}
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/data/GankResponse.java
================================================
package com.yiyuanliu.flipgank.data;
import java.util.List;
import java.util.Map;
/**
* Created by YiyuanLiu on 2016/12/15.
*/
public class GankResponse {
public boolean error;
public Map> results;
public List category;
public boolean hasData() {
return results != null && results.size() > 0;
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/data/History.java
================================================
package com.yiyuanliu.flipgank.data;
/**
* Created by YiyuanLiu on 2016/12/16.
*/
public class History {
public String day;
public boolean hasData;
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/fragment/AboutFragment.java
================================================
package com.yiyuanliu.flipgank.fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.yiyuanliu.flipgank.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class AboutFragment extends Fragment {
private static final String TAG = "AboutFragment";
@BindView(R.id.image_github)
ImageView github;
@BindView(R.id.image_write)
ImageView write;
private Unbinder unbinder;
public AboutFragment() { }
public static AboutFragment newInstance() {
AboutFragment fragment = new AboutFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_about, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
Glide.with(this)
.load(R.drawable.image_github)
.centerCrop()
.into(github);
Glide.with(this)
.load(R.drawable.image_write)
.centerCrop()
.into(write);
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@OnClick(R.id.click_email)
protected void email() {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","yiyuanliu1997@gmail.com", null));
startActivity(Intent.createChooser(intent, "Send Email to yiyuanliu1997@gmail.com"));
}
@OnClick(R.id.click_github)
protected void github() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/yiyuanliu/FlipGank"));
startActivity(intent);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/fragment/CategoryFragment.java
================================================
package com.yiyuanliu.flipgank.fragment;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.adapter.CategoryAdapter;
import com.yiyuanliu.flipgank.data.DataManager;
import com.yiyuanliu.flipgank.view.GridItemDecoration;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class CategoryFragment extends Fragment {
private static final String TAG = "CategoryFragment";
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
private CategoryAdapter mCategoryAdapter;
private Unbinder unbinder;
public CategoryFragment() { }
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_category, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
if (mCategoryAdapter == null) {
mCategoryAdapter = new CategoryAdapter();
}
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
recyclerView.setAdapter(mCategoryAdapter);
recyclerView.addItemDecoration(new GridItemDecoration(getContext()));
DataManager.getInstance(getContext())
.loadCategory()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onLoad, onError);
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
public Action1> onLoad = new Action1>() {
@Override
public void call(List strings) {
mCategoryAdapter.addCategory(strings);
}
};
public Action1 onError = new Action1() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "call: ", throwable);
}
};
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/fragment/GankFragment.java
================================================
package com.yiyuanliu.flipgank.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.yiyuanliu.flipgank.activity.BaseActivity;
import com.yiyuanliu.flipgank.activity.MainActivity;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.adapter.GankAdapter;
import com.yiyuanliu.flipgank.data.DataManager;
import com.yiyuanliu.flipgank.data.GankItem;
import com.yiyuanliu.flipgank.view.flipview.FlipLayoutManager;
import com.yiyuanliu.flipgank.view.flipview.FlipRefreshListener;
import com.yiyuanliu.flipgank.view.flipview.MySnap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class GankFragment extends Fragment implements FlipRefreshListener.Listener, GankAdapter.Listener {
private static final String TAG = "GankFragment";
private static final String ARG_TYPE = "type";
private String mType;
private Unbinder unbinder;
private GankAdapter mAdapter;
private String mLastLoad;
private String mLatest;
private DataManager mDataManager;
private Subscription mSubscription;
private BaseActivity baseActivity;
private boolean mIsLoading;
private FlipRefreshListener mFlipListener;
private boolean mHasMore = true;
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.refresh_hint)
TextView refreshHint;
@BindView(R.id.refresh_icon)
ImageView refreshIcon;
public GankFragment() { }
public static GankFragment newInstance(String type) {
GankFragment fragment = new GankFragment();
Bundle args = new Bundle();
args.putString(ARG_TYPE, type);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mType = getArguments().getString(ARG_TYPE);
}
mDataManager = DataManager.getInstance(getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gank, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
if (mAdapter == null) {
mAdapter = new GankAdapter(getContext(), this);
}
recyclerView.setAdapter(mAdapter);
FlipLayoutManager layoutManager = new FlipLayoutManager(getContext());
recyclerView.setItemAnimator(null);
recyclerView.setLayoutManager(layoutManager);
MySnap snap = new MySnap();
snap.attachToRecyclerView(recyclerView);
if (mFlipListener == null) {
mFlipListener = new FlipRefreshListener(this);
}
recyclerView.addOnScrollListener(mFlipListener);
if (mAdapter.getDataCount() == 0) {
if (mType == null)
loadNew();
else {
loadMore();
}
} else {
mFlipListener.onScrolled(recyclerView, 0, 0);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
if (mSubscription != null) {
mSubscription.unsubscribe();
}
mIsLoading = false;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof BaseActivity) {
baseActivity = (BaseActivity) context;
}
}
@Override
public void onDetach() {
super.onDetach();
baseActivity = null;
}
private void loadMore() {
if (mSubscription != null) {
mSubscription.unsubscribe();
}
mIsLoading = true;
mSubscription = mDataManager.loadMore(mLastLoad)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onMore, new Action1() {
@Override
public void call(Throwable throwable) {
// do nothing
}
});
}
private void loadNew() {
Log.d(TAG, "loadNew: ");
if (mSubscription != null) {
mSubscription.unsubscribe();
}
mIsLoading = true;
//延时一下,效果看起来更明显
mSubscription = mDataManager.loadNew()
.delay(1500, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onNew, onError);
}
private Action1 onError = new Action1() {
@Override
public void call(Throwable throwable) {
mIsLoading = false;
Log.e(TAG, "onError", throwable);
if (baseActivity != null) {
baseActivity.showInfo("加载失败");
} else {
Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
}
}
};
private Action1> onNew = new Action1>() {
@Override
public void call(List gankItemList) {
mIsLoading = false;
if (gankItemList.size() > 0) {
mHasMore = true;
final String latest = gankItemList.get(0).day;
if (!latest.equals(mLatest)) {
mLatest = latest;
mLastLoad = latest;
mAdapter.clear();
if (mType != null) {
Iterator itemIterator = gankItemList.listIterator();
while (itemIterator.hasNext()) {
if (!itemIterator.next().type.equals(mType)) {
itemIterator.remove();
}
}
}
mAdapter.addData(gankItemList);
recyclerView.scrollToPosition(0);
if (baseActivity != null) {
baseActivity.setLoading(false);
}
} else if (baseActivity != null) {
baseActivity.showInfo("已经是最新内容");
}
}
mFlipListener.onScrolled(recyclerView, 0, 0);
}
};
private Action1> onMore = new Action1>() {
@Override
public void call(List gankItemList) {
mIsLoading = false;
if (gankItemList.size() > 0) {
mLastLoad = gankItemList.get(0).day;
Log.d(TAG, "onMore: " + mLastLoad + new Gson().toJson(gankItemList.get(0)));
if (mType != null && !mType.equals("like")) {
Iterator itemIterator = gankItemList.listIterator();
while (itemIterator.hasNext()) {
if (!itemIterator.next().type.equals(mType)) {
itemIterator.remove();
}
}
}
if (mType != null && mType.equals("like")) {
Iterator itemIterator = gankItemList.listIterator();
while (itemIterator.hasNext()) {
if (!itemIterator.next().like) {
itemIterator.remove();
}
}
}
mAdapter.addData(gankItemList);
if (mLatest == null) {
mLatest = mLastLoad;
}
} else {
mHasMore = false;
mAdapter.setHasMore(mHasMore);
}
mAdapter.setHasMore(mHasMore);
mFlipListener.onScrolled(recyclerView, 0, 0);
}
};
@Override
public void onRefresh() {
loadNew();
if (baseActivity != null) {
baseActivity.setLoading(true);
}
}
@Override
public void onDrag(float percent, boolean shouldRefresh) {
if (refreshHint != null && getView() != null) {
if (shouldRefresh) {
refreshHint.setText("松开可以刷新");
} else {
refreshHint.setText("下拉刷新页面");
}
View view = getView();
int from = 0x00;
int to = 0x30;
int now = (from + (int)((to - from) * percent));
int color = 0xFF << 24 | now << 16 | now << 8 | now;
view.setBackgroundColor(color);
refreshIcon.setRotation(percent * 360);
}
}
@Override
public void onLoadMore() {
if (!mIsLoading && mHasMore) {
loadMore();
}
}
@Override
public void showInfo(String info) {
if (baseActivity != null) {
baseActivity.showInfo(info);
}
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/GankBottom.java
================================================
package com.yiyuanliu.flipgank.view;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.data.GankItem;
import com.yiyuanliu.flipgank.view.flipview.FlipRefreshListener;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by YiyuanLiu on 2016/12/21.
*/
public class GankBottom extends LinearLayout implements GankItemView {
@BindView(R.id.title)
TextView title;
@BindView(R.id.type)
TextView type;
@BindView(R.id.url)
TextView url;
@BindView(R.id.who)
TextView who;
@BindView(R.id.time)
TextView time;
public GankBottom(Context context) {
super(context);
}
public GankBottom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GankBottom(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.bind(this);
}
@Override
public void bind(final GankItem gankItem, final GankItemView.Listener listener) {
if (gankItem != null) {
title.setText(gankItem.desc);
type.setText(gankItem.type);
if (gankItem.who == null) {
who.setVisibility(GONE);
} else {
who.setVisibility(VISIBLE);
who.setText(gankItem.who);
}
url.setText(gankItem.url);
time.setText(gankItem.day);
}
}
@OnClick(R.id.url)
void openUrl() {
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/GankItemView.java
================================================
package com.yiyuanliu.flipgank.view;
import com.yiyuanliu.flipgank.data.GankItem;
/**
* Created by YiyuanLiu on 2016/12/20.
*/
public interface GankItemView {
void bind(GankItem gankItem, Listener listener);
interface Listener {
void open(GankItem gankItem);
void showBottomSheet(GankItem gankItem);
void like(GankItem gankItem);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/GridItemDecoration.java
================================================
package com.yiyuanliu.flipgank.view;
import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.Collections;
/**
* Created by YiyuanLiu on 2016/12/22.
*/
public class GridItemDecoration extends RecyclerView.ItemDecoration {
private int dimen;
public GridItemDecoration(Context context) {
dimen = (int) (context.getResources().getDisplayMetrics().density * 1);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
if (position % 2 == 0) {
outRect.right += dimen;
} else {
outRect.left += dimen;
}
if (position > 1) {
outRect.top += dimen;
}
if (position / 2 < state.getItemCount() / 2) {
outRect.bottom += dimen;
}
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/HeadItem.java
================================================
package com.yiyuanliu.flipgank.view;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.data.GankItem;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
/**
* Created by YiyuanLiu on 2016/12/20.
*/
public class HeadItem extends FrameLayout implements GankItemView {
private static final String TAG = "HeadItem";
@BindView(R.id.image)
ImageView image;
public HeadItem(Context context) {
super(context);
}
public HeadItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HeadItem(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void bind(GankItem gankItem, Listener listener) {
if (gankItem != null) {
if (!TextUtils.isEmpty(gankItem.getImage())) {
Glide.with(getContext())
.load(gankItem.getImage())
.centerCrop()
.into(image);
} else {
Log.e(TAG, "no image " + new Gson().toJson(gankItem));
}
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.bind(this);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/NormalItem.java
================================================
package com.yiyuanliu.flipgank.view;
import android.content.Context;
import android.content.res.ColorStateList;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.yiyuanliu.flipgank.R;
import com.yiyuanliu.flipgank.data.GankItem;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by YiyuanLiu on 2016/12/20.
*/
public class NormalItem extends FrameLayout implements GankItemView {
private static final String TAG = "NormalItem";
private int width;
@BindView(R.id.title)
TextView title;
@BindView(R.id.type)
TextView type;
@Nullable @BindView(R.id.image)
ImageView image;
@BindView(R.id.show_bottom)
ImageButton showBottom;
@BindView(R.id.like)
ImageButton likeButton;
public NormalItem(Context context) {
super(context);
}
public NormalItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NormalItem(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void bind(final GankItem gankItem, final Listener listener) {
if(gankItem != null) {
title.setText(gankItem.desc);
type.setText(gankItem.type);
if (image != null) {
if (TextUtils.isEmpty(gankItem.getImage())) {
image.setVisibility(GONE);
} else {
image.setVisibility(VISIBLE);
if (width == 0) {
width = (int) (getResources().getDisplayMetrics().density * 100);
}
Glide.with(getContext())
.load(gankItem.getImage() + "?imageView2/1/w/" + width)
.placeholder(R.drawable.drawable_placeholder)
.centerCrop()
.into(image);
}
}
if (gankItem.like) {
likeButton.setImageResource(R.drawable.bt_like);
} else {
likeButton.setImageResource(R.drawable.bt_unlike);
}
} else {
title.setText(null);
type.setText(null);
if (image!= null) {
image.setVisibility(GONE);
}
}
showBottom.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
listener.showBottomSheet(gankItem);
}
});
likeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
gankItem.like = !gankItem.like;
if (gankItem.like) {
likeButton.setImageResource(R.drawable.bt_like);
} else {
likeButton.setImageResource(R.drawable.bt_unlike);
}
listener.like(gankItem);
}
});
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
listener.open(gankItem);
}
});
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.bind(this);
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/flipview/FlipCard.java
================================================
package com.yiyuanliu.flipgank.view.flipview;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.FrameLayout;
/**
* Created by YiyuanLiu on 2016/12/15.
*/
public class FlipCard extends FrameLayout {
private static final String TAG = "FlipCard";
private Paint mScrimPaint;
private Camera mCamera;
private Matrix mMatrix;
private boolean mIsForground;
private float mPercent;
public FlipCard(Context context) {
this(context, null);
}
public FlipCard(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FlipCard(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mScrimPaint = new Paint();
mCamera = new Camera();
mMatrix = new Matrix();
}
public void setState(boolean isForground, float percent) {
mIsForground = isForground;
mPercent = percent;
}
@Override
public void draw(Canvas canvas) {
if (mPercent == 0) {
super.draw(canvas);
return;
}
final int height = canvas.getHeight();
final int width = canvas.getWidth();
final float percent = mPercent > 0 ? mPercent : -mPercent;
if (mIsForground) {
// clip card effect for forground view
// draw part1
int save1 = canvas.save();
if (mPercent > 0) {
canvas.clipRect(0, 0, width, height / 2);
} else {
canvas.clipRect(0, height / 2, width, height);
}
super.draw(canvas);
canvas.restoreToCount(save1);
// draw part2
if (mPercent < 0) {
canvas.clipRect(0, 0, width, height / 2);
} else {
canvas.clipRect(0, height / 2, width, height);
}
mCamera.save();
mCamera.setLocation(0f, 0f, -80);
mCamera.rotateX(mPercent * 180);
mCamera.getMatrix(mMatrix);
mCamera.restore();
mMatrix.preTranslate(-width / 2, -height / 2);
mMatrix.postTranslate(width / 2, height / 2);
canvas.concat(mMatrix);
super.draw(canvas);
mScrimPaint.setColor(0x08000000);
canvas.drawRect(0, 0, width, height, mScrimPaint);
} else {
// draw shadow for underground view
final int scrimColor = (int) (0xff * (1 - percent * 2)) << 24;
mScrimPaint.setColor(scrimColor);
if (mPercent < 0) {
canvas.clipRect(0, 0, width, height / 2);
} else {
canvas.clipRect(0, height / 2, width, height);
}
super.draw(canvas);
canvas.drawRect(0, 0, width, height, mScrimPaint);
}
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/flipview/FlipLayoutManager.java
================================================
package com.yiyuanliu.flipgank.view.flipview;
import android.content.Context;
import android.graphics.PointF;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
public class FlipLayoutManager extends RecyclerView.LayoutManager implements RecyclerView.SmoothScroller.ScrollVectorProvider {
private static final String TAG = "FlipLayoutManager";
private static final int MIN_VY = 200;
private int mPosition;
private int mPositionOffset;
private int mMinVy;
private int mPendingPosition;
public FlipLayoutManager(Context context) {
mMinVy = (int) (context.getResources().getDisplayMetrics().density * MIN_VY);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
mPosition = savedState.position;
mPositionOffset = savedState.positionOffset;
mPendingPosition = savedState.pendingPosition;
}
@Override
public Parcelable onSaveInstanceState() {
return new SavedState(mPosition, mPositionOffset, mPendingPosition);
}
public boolean onRefreshPage() {
return mPosition == 0 && mPositionOffset < 0;
}
public float getRefreshPercent() {
int max = (int) (getItemHeightInPositon() / 5 * 2);
return - mPositionOffset / (float)max;
}
public int calculateDistance(View view) {
int pos = getPosition(view);
final int now = getItemHeightInPositon() * mPosition + mPositionOffset;
final int to = getItemHeightInPositon() * pos;
return to - now;
}
public int findTargetPosition(int vY) {
int ans = mPosition;
int absV = vY > 0 ? vY : -vY;
if (absV > mMinVy) {
if (vY * mPositionOffset > 0) {
int d = vY > 0 ? 1 : -1;
ans += d;
} else {
ans = mPosition;
}
} else {
ans = mPosition;
}
int count = getItemCount();
if (count == 0) {
return 0;
}
ans = Math.min(count - 1, Math.max(0, ans));
return ans;
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (state.getItemCount() == 0) {
removeAndRecycleAllViews(recycler);
return;
}
if (mPendingPosition != -1) {
mPositionOffset = 0;
mPosition = mPendingPosition;
mPendingPosition = -1;
}
fill(recycler, state);
}
// 有 bug 继续改
private void fill(RecyclerView.Recycler recycler, RecyclerView.State state) {
checkPosition(state);
View primary = null;
View previous = null;
View next = null;
detachAndScrapAttachedViews(recycler);
primary = recycler.getViewForPosition(mPosition);
if (mPosition + 1 > 0 && mPosition + 1 < state.getItemCount()) {
next = recycler.getViewForPosition(mPosition + 1);
}
if (mPosition - 1 > 0 && mPosition - 1 < state.getItemCount()) {
previous = recycler.getViewForPosition(mPosition - 1);
}
View secondary = null;
final int nextPos = mPositionOffset > 0 ? mPosition + 1 : mPosition - 1;
if (mPositionOffset != 0 && nextPos >= 0 && nextPos < state.getItemCount()) {
secondary = mPositionOffset > 0 ? next : previous;
secondary = secondary != null ? secondary : recycler.getViewForPosition(nextPos);
addView(secondary);
measureChildWithMargins(secondary, 0, 0);
layoutDecorated(secondary, 0, 0, getWidth(), getHeight());
}
if (secondary != previous && previous != null) {
recycler.recycleView(previous);
}
if (secondary != next && next != null) {
recycler.recycleView(next);
}
addView(primary);
measureChildWithMargins(primary, 0, 0);
layoutDecorated(primary, 0, 0, getWidth(), getHeight());
if (primary instanceof FlipCard && (secondary == null || secondary instanceof FlipCard)) {
final float percent = (float)mPositionOffset / getItemHeightInPositon();
if (secondary == null) {
((FlipCard) primary).setState(true, percent);
} else {
((FlipCard) secondary).setState(false, percent);
((FlipCard) primary).setState(true, percent);
}
} else {
throw new IllegalStateException("itemView should be instance of FlipCard");
}
}
private void checkPosition(RecyclerView.State state) {
final int itemHeight = getItemHeightInPositon();
final int total = mPosition * itemHeight + mPositionOffset;
final int max = (state.getItemCount() - 1) * itemHeight + itemHeight / 5 * 2;
int pos = Math.max(-itemHeight / 5 * 2, Math.min(total, max));
mPosition = Math.round(pos / (float)itemHeight);
mPosition = mPosition >= 0 ? mPosition : 0;
mPositionOffset = (int) (pos - mPosition * itemHeight);
}
@Override
public boolean canScrollVertically() {
return true;
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
final int before = mPosition * getItemHeightInPositon() + mPositionOffset;
mPositionOffset += dy;
checkPosition(state);
final int after = mPosition * getItemHeightInPositon() + mPositionOffset;
final int ans = (int) (after - before);
fill(recycler, state);
return ans;
}
@Override
public void scrollToPosition(int position) {
mPosition = position;
mPositionOffset = 0;
requestLayout();
Log.d(TAG, "scrollToPosition " + position + " position " + mPosition + " positionOffset " + mPositionOffset);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
Log.d(TAG, "smoothScrollTo " + position + " position " + mPosition + " positionOffset " + mPositionOffset);
FlipScroller scroller = new FlipScroller(recyclerView.getContext());
scroller.setTargetPosition(position);
startSmoothScroll(scroller);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
int dir = 0;
int now = mPosition * getItemHeightInPositon() + mPositionOffset;
int to = targetPosition * getItemHeightInPositon();
if (now > to) {
dir = -1;
} else if (now < to) {
dir = 1;
}
Log.d(TAG, "computeScrollVector " + dir + " now " + mPosition + " target " + targetPosition);
return new PointF(0, dir);
}
public View findSnapView() {
for (int i = 0;i < getChildCount(); i ++ ){
View child = getChildAt(i);
if (getPosition(child) == mPosition) {
return child;
}
}
return null;
}
private int getItemHeightInPositon() {
return getHeight() * 2 / 3;
}
public boolean shouldLoadMore() {
return getItemCount() - mPosition < 3;
}
private class FlipScroller extends LinearSmoothScroller {
private static final String TAG = "FlipScroller";
public FlipScroller(Context context) {
super(context);
}
@Override
public int calculateDyToMakeVisible(View view, int snapPreference) {
final int position = getPosition(view);
final int now = mPositionOffset + mPosition * getItemHeightInPositon();
final int to = getPosition(view) * getItemHeightInPositon();
Log.d(TAG, "calculateDyToMakeVisible: position " + position + " ans " + (to - now));
return (now - to);
}
@Override
public int calculateDxToMakeVisible(View view, int snapPreference) {
return 0;
}
}
private static class SavedState implements Parcelable {
private int position;
private int positionOffset;
private int pendingPosition;
SavedState(int position, int positionOffset, int pendingPosition) {
this.position = position;
this.positionOffset = positionOffset;
this.pendingPosition = pendingPosition;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(position);
dest.writeInt(positionOffset);
dest.writeInt(pendingPosition);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
@Override
public SavedState createFromParcel(Parcel source) {
final int position = source.readInt();
final int positionOffset = source.readInt();
final int pendingPosition = source.readInt();
SavedState savedState = new SavedState(position, positionOffset, pendingPosition);
return savedState;
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/flipview/FlipRefreshListener.java
================================================
package com.yiyuanliu.flipgank.view.flipview;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
/**
* Created by YiyuanLiu on 2016/12/20.
*/
public class FlipRefreshListener extends RecyclerView.OnScrollListener {
private Listener mListener;
public FlipRefreshListener(@NonNull Listener listener) {
mListener = listener;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager != null && layoutManager instanceof FlipLayoutManager) {
FlipLayoutManager flipLayoutManager = (FlipLayoutManager) layoutManager;
if (flipLayoutManager.onRefreshPage()) {
float percent = flipLayoutManager.getRefreshPercent();
boolean shouldRefresh = percent > 0.7f;
mListener.onDrag(percent, shouldRefresh);
} else if (flipLayoutManager.shouldLoadMore()){
mListener.onLoadMore();
}
} else {
throw new IllegalStateException();
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager != null && layoutManager instanceof FlipLayoutManager) {
FlipLayoutManager flipLayoutManager = (FlipLayoutManager) layoutManager;
if (!flipLayoutManager.onRefreshPage()) {
return;
}
float percent = flipLayoutManager.getRefreshPercent();
boolean shouldRefresh = percent > 0.7f;
if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
if (shouldRefresh) {
mListener.onRefresh();
}
}
}
}
public interface Listener {
void onRefresh();
void onDrag(float percent, boolean shouldRefresh);
void onLoadMore();
}
}
================================================
FILE: app/src/main/java/com/yiyuanliu/flipgank/view/flipview/MySnap.java
================================================
package com.yiyuanliu.flipgank.view.flipview;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.Log;
import android.view.View;
/**
* Created by YiyuanLiu on 2016/12/15.
*/
public class MySnap extends SnapHelper {
private static final String TAG = "MySnap";
@Nullable
@Override
public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) {
if (layoutManager instanceof FlipLayoutManager) {
return new int[]{0, ((FlipLayoutManager) layoutManager).calculateDistance(targetView)};
} else {
throw new RuntimeException();
}
}
@Nullable
@Override
public View findSnapView(RecyclerView.LayoutManager layoutManager) {
FlipLayoutManager flipLayoutManager = (FlipLayoutManager) layoutManager;
return flipLayoutManager.findSnapView();
}
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
if (layoutManager instanceof FlipLayoutManager) {
return ((FlipLayoutManager) layoutManager).findTargetPosition(velocityY);
} else {
throw new RuntimeException();
}
}
}
================================================
FILE: app/src/main/res/anim/anim_scale_in.xml
================================================
================================================
FILE: app/src/main/res/anim/anim_scale_out.xml
================================================
================================================
FILE: app/src/main/res/anim/left_in.xml
================================================
================================================
FILE: app/src/main/res/anim/left_out.xml
================================================
================================================
FILE: app/src/main/res/color/color_icon_hint.xml
================================================
================================================
FILE: app/src/main/res/drawable/bg_category.xml
================================================
================================================
FILE: app/src/main/res/drawable/bg_circle.xml
================================================
================================================
FILE: app/src/main/res/drawable/bg_info.xml
================================================
================================================
FILE: app/src/main/res/drawable/bg_type.xml
================================================
================================================
FILE: app/src/main/res/drawable/bt_like.xml
================================================
================================================
FILE: app/src/main/res/drawable/bt_open.xml
================================================
-
================================================
FILE: app/src/main/res/drawable/bt_show_bottom.xml
================================================
-
================================================
FILE: app/src/main/res/drawable/bt_unlike.xml
================================================
================================================
FILE: app/src/main/res/drawable/drawable_loading.xml
================================================
================================================
FILE: app/src/main/res/drawable/drawable_placeholder.xml
================================================
================================================
FILE: app/src/main/res/drawable/icon_about.xml
================================================
-
-
================================================
FILE: app/src/main/res/drawable/icon_category.xml
================================================
-
-
================================================
FILE: app/src/main/res/drawable/icon_main.xml
================================================
-
-
================================================
FILE: app/src/main/res/drawable/shadow_bottom.xml
================================================
================================================
FILE: app/src/main/res/drawable/shadow_top.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_category.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_gank_view.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/layout/bottom_sheet.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_about.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_category.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_gank.xml
================================================
================================================
FILE: app/src/main/res/layout/item_category.xml
================================================
================================================
FILE: app/src/main/res/layout/item_head.xml
================================================
================================================
FILE: app/src/main/res/layout/item_normal.xml
================================================
================================================
FILE: app/src/main/res/layout/item_tab.xml
================================================
================================================
FILE: app/src/main/res/layout/item_text.xml
================================================
================================================
FILE: app/src/main/res/layout/layout_divider_hor.xml
================================================
================================================
FILE: app/src/main/res/layout/layout_divider_vertical.xml
================================================
================================================
FILE: app/src/main/res/layout/page_first.xml
================================================
================================================
FILE: app/src/main/res/layout/page_loading.xml
================================================
================================================
FILE: app/src/main/res/layout/page_normal.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#FF2727
#FF2727
#FF2727
#000000
#00000A
#37373A
#FFFFFF
#CCCCCC
#FFFFFFFF
#FFFFFF
================================================
FILE: app/src/main/res/values/dimens.xml
================================================
16dp
16dp
================================================
FILE: app/src/main/res/values/strings.xml
================================================
FlipGank
Kickstarter Android 源码开源啦! 一个仿探探上传相片的widget,基于xmuSistone的demo, 提供gradle import,添加上传照片功能以及各种回调,api,方便使用
DragVideo,一种在播放视频时,可以任意拖拽视频的方案
Hello blank fragment
================================================
FILE: app/src/main/res/values/styles.xml
================================================
#FFFFFF
#101010
================================================
FILE: app/src/main/res/values-v21/styles.xml
================================================
================================================
FILE: app/src/main/res/values-w820dp/dimens.xml
================================================
64dp
================================================
FILE: app/src/test/java/com/yiyuanliu/flipgank/ExampleUnitTest.java
================================================
package com.yiyuanliu.flipgank;
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.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
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.
#
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
#
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx1024m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
#
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#Wed Dec 28 20:37:53 CST 2016
org.gradle.jvmargs=-Xmx1536m
================================================
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'