Repository: yanzhenjie/NoFragment
Branch: master
Commit: c0c56f612635
Files: 41
Total size: 89.3 KB
Directory structure:
gitextract_ta7k6lla/
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── config.gradle
├── fragment/
│ ├── build.gradle
│ ├── maven.gradle
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── yanzhenjie/
│ └── fragment/
│ ├── CompatActivity.java
│ ├── NoFragment.java
│ └── ResultCode.java
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── sample/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── com/
│ │ └── yanzhenjie/
│ │ └── fragment/
│ │ └── sample/
│ │ ├── MainActivity.java
│ │ ├── adapter/
│ │ │ └── RecyclerAdapter.java
│ │ └── fragment/
│ │ ├── ArgumentFragment.java
│ │ ├── MainFragment.java
│ │ ├── MoreMenuFragment.java
│ │ ├── StackFragment.java
│ │ ├── StackNewFragment.java
│ │ └── StartResultFragment.java
│ └── res/
│ ├── layout/
│ │ ├── activity_main.xml
│ │ ├── fragment_argument.xml
│ │ ├── fragment_main.xml
│ │ ├── fragment_menu.xml
│ │ ├── fragment_result.xml
│ │ ├── fragment_stack.xml
│ │ ├── fragment_stack_new.xml
│ │ └── item.xml
│ ├── menu/
│ │ ├── menu_fragment_main.xml
│ │ └── menu_fragment_setting.xml
│ └── values/
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.iml
.gradle
/local.properties
/build
/.gradle/
/.idea/
/sample/build/
/fragment/build/
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Yan Zhenjie
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
================================================
严振杰的主页:[http://www.yanzhenjie.com](http://www.yanzhenjie.com)
严振杰的博客:[http://blog.yanzhenjie.com](http://blog.yanzhenjie.com)
**欢迎加入QQ技术交流群:[46523908](http://jq.qq.com/?_wv=1027&k=40hvC7E)**
关于Fragment、NoFragment的使用看博客:[【2016Ending,2017Starting】NoFragment之Fragment玩法新姿势](http://blog.csdn.net/yanzhenjie1003/article/details/54562328)。
# 特点
1. 支持传统`Fragment`的所有用法。
2. 支持`startFragmentForResult(Fragment)`、`onFragmentResult(int, int, Bundle)`,原生只有Activity。
3. 支持同一个`Fragment`启动多个实例。
5. 支持自动维护`Back Stack`,不会错乱。
6. 支持在`Fragment`中直接`setToolbar()`、`setTitle()`、`displayHomeButton()`。
7. 返回键和`homeButton`自动处理,支持开发者拦截处理。
8. 支持`ActionBar Menu`、溢出`Menu`等。
9. 开发者不用管跳转逻辑、back键处理、Toolbar加载菜单等。
# 使用方法
* Gradle一句话远程依赖
```groovy
compile 'com.yanzhenjie:fragment:1.0.1'
```
* Maven:
```xml
com.yanzhenjie
fragment
1.0.1
pom
```
* Eclipse ADT
请放弃治疗。
# 图示
第一种,结合ToolBar、Menu的演示:
第二种,结合Toolbar、Menu + OverFlower的演示:
第三种,`startFragmentForResult()`、`onFragmentResult()`演示:
第四种,不保存的在回退栈的演示:
# 代码展示
你的宿主`Activity`需要继承`CompatActivity`,然后启动一个`Fragment`:
```java
public class MainActivity extends CompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* 一句话即可,不要怀疑自己的眼睛,这是真的。
*/
startFragment(MainFragment.class);
}
@Override
protected int fragmentLayoutId() {
return R.id.fragment_root;
}
}
```
之后在Fragment中互相跳转,你可以不用管物理Back键被按下之类的:
## 一、以`standard`模式启动一个`Fragment`
```java
startFragment(MoreMenuFragment.class);
```
## 二、以`startActivityForResult()`方式启动一个`Fragment`
```java
// 启动,等待回调结果。
startFragmentForResult(StartResultFragment.class, 100);
// 不论怎样回来都会回调onFragmentResult()。
@Override
public void onFragmentResult(int requestCode, int resultCode, @Nullable Bundle result) {
switch (requestCode) {
case 100: {
if (resultCode == RESULT_OK) {
// 操作成功:result就是调用的Fragment返回的结果。
} else if (resultCode == RESULT_CANCELED) {
// 操作取消。
}
break;
}
}
}
```
在`StartResultFragment`中如果要返回结果,那么:
```java
Bundle bundle = new Bundle();
bundle.putString("message", result);
setResult(RESULT_OK, bundle);
finish();
```
当然你也不设置,那么`resultCode`的默认值是`RESULT_CANCELED`。
## 三、跳转时带参数
```java
// 封装参数:
Bundle bundle = new Bundle();
bundle.putString("hehe", "呵呵哒");
bundle.putString("meng", "萌萌哒");
bundle.putString("bang", "棒棒哒");
bundle.putString("meme", "么么哒");
// 在Activity中或者Fragment调用此方法:
NoFragment fragment = fragment(ArgumentFragment.class, bundle);
// 最后启动:
startFragment(fragment);
```
## 四、跳转的`Fragment`不保存在`Back Stack`
这种方式显示的`fragment`中如果调用了其它`fragment`,从其它`fragment`中回来时,这个`fragment`将会跳过,不会显示,也就是说:A-B-C-[back]-A,从A到B,B不加入回退栈,B再到C,C按下返回键,或者调用`finish()`方法,将会直接回到A。
```java
startFragment(StackFragment.class, false);
```
## 五、同一个Fragment,启动多个实例
```java
startFragment(MoreMenuFragment.class);
startFragment(MoreMenuFragment.class);
startFragment(MoreMenuFragment.class);
startFragment(MoreMenuFragment.class);
```
比如我们这里调用四次,那么回退栈中有四个`MoreMenuFragment`,按下返回键时将一个个退出。
## 六、Toolbar菜单的加载和处理
我们知道MD设计中,Toolbar的菜单很好看,而且利用Toolbar也很好加载,那么NoFragment也是完美支持的,当重写了`onCreateOptionsMenu()`方法后,调用`setToolbar(Toolbar)`方法时,将会调用`onCreateOptionsMenu()`方法,此时你就该加载菜单了,当然也只需要一句话。
```java
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Load your menu.
inflater.inflate(R.menu.menu_fragment_main, menu);
}
```
当用户点击meun的item时将会回调这个方法,和原生Activity是一样的。
```java
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle menu item click.
int id = item.getItemId();
switch (id) {
case R.id.action_settings: {
Snackbar.make(mToolbar, R.string.action_settings, Snackbar.LENGTH_SHORT).show();
break;
}
case R.id.action_exit: {
Snackbar.make(mToolbar, R.string.action_exit, Snackbar.LENGTH_SHORT).show();
break;
}
}
return true;
}
```
## 七、Toolbar的返回按钮的处理
在正常开发中给Toolbar设置返回按钮也要好几行代码的,如果使用了NoFragment,那么:
```java
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 首先设置Toolbar:
setToolbar(mToolbar);
// 设置标题:
setTitle(R.string.title_fragment_main);
// 显示返回按钮,图标开发者指定:
displayHomeAsUpEnabled(R.drawable.ic_close_white);
}
```
设置了返回按钮后,用户点击返回按钮将自动杀死当前`Fragment`,当然你也可以拦截用户的返回行为:
```java
@Override
public boolean onInterceptToolbarBack() {
// 返回true将拦截,返回false将不拦截。
return true;
}
```
# 混淆
```text
-keep public class * extends android.support.v4.app.Fragment
```
# License
```text
Copyright 2017 Yan Zhenjie
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: build.gradle
================================================
apply from: "config.gradle"
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: config.gradle
================================================
ext {
plugins = [
library : 'com.android.library',
application: 'com.android.application',
maven : 'com.github.dcendents.android-maven',
bintray : 'com.jfrog.bintray'
]
android = [
// build.
compileSdkVersion: 25,
buildToolsVersion: "25.0.2",
// defaultConfig.
applicationId : "com.yanzhenjie.fragment.sample",
minSdkVersion : 11,
targetSdkVersion : 25,
versionCode : 11,
versionName : "1.01",
]
dependencies = [
// android-support
design : 'com.android.support:design:25.3.1',
appcompat : 'com.android.support:appcompat-v7:25.3.1',
permission : 'com.yanzhenjie:permission:1.0.5',
fragment : 'com.yanzhenjie:fragment:1.0.2',
alertdialog: 'com.yanzhenjie.alertdialog:alertdialog:1.0.0'
]
}
================================================
FILE: fragment/build.gradle
================================================
apply plugin: rootProject.ext.plugins.library
android {
compileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion
defaultConfig {
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
}
}
dependencies {
compile rootProject.ext.dependencies.appcompat
}
apply from: "maven.gradle"
================================================
FILE: fragment/maven.gradle
================================================
apply plugin: rootProject.ext.plugins.maven
apply plugin: rootProject.ext.plugins.bintray
version = "1.0.2"
def siteUrl = 'https://github.com/yanzhenjie/NoFragment'
def gitUrl = 'git@github.com:yanzhenjie/NoFragment.git'
group = "com.yanzhenjie"
install {
repositories.mavenInstaller {
pom {
project {
packaging 'aar'
name 'Fragment for Android'
description 'Fragment for Android'
url siteUrl
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id 'yanzhenjie'
name 'yanzhenjie'
email 'smallajax@foxmail.com'
}
}
scm {
connection gitUrl
developerConnection gitUrl
url siteUrl
}
}
}
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
failOnError false
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar
archives sourcesJar
}
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
bintray {
user = properties.getProperty("bintray.user")
key = properties.getProperty("bintray.apikey")
configurations = ['archives']
pkg {
repo = "maven"
name = "fragment"
userOrg = 'yolanda'
websiteUrl = siteUrl
vcsUrl = gitUrl
licenses = ["Apache-2.0"]
publish = true
version {
gpg {
sign = true
passphrase = properties.getProperty("bintray.gpg.password")
}
}
}
}
================================================
FILE: fragment/src/main/AndroidManifest.xml
================================================
================================================
FILE: fragment/src/main/java/com/yanzhenjie/fragment/CompatActivity.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
Must extends CompatActivity.
* Created by Yan Zhenjie on 2017/1/13.
*/
public abstract class CompatActivity extends AppCompatActivity {
public static final int REQUEST_CODE_INVALID = -1;
private FragmentManager mFManager;
private AtomicInteger mAtomicInteger = new AtomicInteger();
private List mFragmentStack = new ArrayList<>();
private Map mFragmentEntityMap = new HashMap<>();
static class FragmentStackEntity {
private FragmentStackEntity() {
}
private boolean isSticky = false;
private int requestCode = REQUEST_CODE_INVALID;
@ResultCode
int resultCode = RESULT_CANCELED;
Bundle result = null;
}
public final T fragment(Class fragmentClass) {
//noinspection unchecked
return (T) Fragment.instantiate(this, fragmentClass.getName());
}
public final T fragment(Class fragmentClass, Bundle bundle) {
//noinspection unchecked
return (T) Fragment.instantiate(this, fragmentClass.getName(), bundle);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFManager = getSupportFragmentManager();
}
/**
* Show a fragment.
*
* @param clazz fragment class.
*/
public final void startFragment(Class clazz) {
try {
NoFragment targetFragment = clazz.newInstance();
startFragment(null, targetFragment, true, REQUEST_CODE_INVALID);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a fragment.
*
* @param clazz fragment class.
* @param stickyStack sticky to back stack.
*/
public final void startFragment(Class clazz, boolean stickyStack) {
try {
NoFragment targetFragment = clazz.newInstance();
startFragment(null, targetFragment, stickyStack, REQUEST_CODE_INVALID);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a fragment.
*
* @param targetFragment fragment to display.
* @param {@link NoFragment}.
*/
public final void startFragment(T targetFragment) {
startFragment(null, targetFragment, true, REQUEST_CODE_INVALID);
}
/**
* Show a fragment.
*
* @param targetFragment fragment to display.
* @param stickyStack sticky back stack.
* @param {@link NoFragment}.
*/
public final void startFragment(T targetFragment, boolean stickyStack) {
startFragment(null, targetFragment, stickyStack, REQUEST_CODE_INVALID);
}
/**
* Show a fragment for result.
*
* @param clazz fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
* @deprecated use {@link #startFragmentForResult(Class, int)} instead.
*/
@Deprecated
public final void startFragmentForResquest(Class clazz, int requestCode) {
startFragmentForResult(clazz, requestCode);
}
/**
* Show a fragment for result.
*
* @param targetFragment fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
* @deprecated use {@link #startFragmentForResult(NoFragment, int)} instead.
*/
@Deprecated
public final void startFragmentForResquest(T targetFragment, int requestCode) {
startFragmentForResult(targetFragment, requestCode);
}
/**
* Show a fragment for result.
*
* @param clazz fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
*/
public final void startFragmentForResult(Class clazz, int requestCode) {
if (requestCode == REQUEST_CODE_INVALID)
throw new IllegalArgumentException("The requestCode must be positive integer.");
try {
NoFragment targetFragment = clazz.newInstance();
startFragment(null, targetFragment, true, requestCode);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a fragment for result.
*
* @param targetFragment fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
*/
public final void startFragmentForResult(T targetFragment, int requestCode) {
if (requestCode == REQUEST_CODE_INVALID)
throw new IllegalArgumentException("The requestCode must be positive integer.");
startFragment(null, targetFragment, true, requestCode);
}
/**
* Show a fragment.
*
* @param thisFragment Now show fragment, can be null.
* @param thatFragment fragment to display.
* @param stickyStack sticky back stack.
* @param requestCode requestCode.
* @param {@link NoFragment}.
*/
protected final void startFragment(T thisFragment, T thatFragment,
boolean stickyStack, int requestCode) {
FragmentTransaction fragmentTransaction = mFManager.beginTransaction();
if (thisFragment != null) {
FragmentStackEntity thisStackEntity = mFragmentEntityMap.get(thisFragment);
if (thisStackEntity != null) {
if (thisStackEntity.isSticky) {
thisFragment.onPause();
thisFragment.onStop();
fragmentTransaction.hide(thisFragment);
} else {
fragmentTransaction.remove(thisFragment).commit();
fragmentTransaction.commitNow();
fragmentTransaction = mFManager.beginTransaction();
mFragmentEntityMap.remove(thisFragment);
mFragmentStack.remove(thisFragment);
}
}
}
String fragmentTag = thatFragment.getClass().getSimpleName() + mAtomicInteger.incrementAndGet();
fragmentTransaction.add(fragmentLayoutId(), thatFragment, fragmentTag);
fragmentTransaction.addToBackStack(fragmentTag);
fragmentTransaction.commit();
FragmentStackEntity fragmentStackEntity = new FragmentStackEntity();
fragmentStackEntity.isSticky = stickyStack;
fragmentStackEntity.requestCode = requestCode;
thatFragment.setStackEntity(fragmentStackEntity);
mFragmentEntityMap.put(thatFragment, fragmentStackEntity);
mFragmentStack.add(thatFragment);
}
/**
* When the back off.
*/
protected final boolean onBackStackFragment() {
if (mFragmentStack.size() > 1) {
mFManager.popBackStack();
NoFragment inFragment = mFragmentStack.get(mFragmentStack.size() - 2);
FragmentTransaction fragmentTransaction = mFManager.beginTransaction();
fragmentTransaction.show(inFragment);
fragmentTransaction.commit();
NoFragment outFragment = mFragmentStack.get(mFragmentStack.size() - 1);
inFragment.onResume();
FragmentStackEntity stackEntity = mFragmentEntityMap.get(outFragment);
mFragmentStack.remove(outFragment);
mFragmentEntityMap.remove(outFragment);
if (stackEntity.requestCode != REQUEST_CODE_INVALID) {
inFragment.onFragmentResult(stackEntity.requestCode, stackEntity.resultCode, stackEntity.result);
}
return true;
}
return false;
}
@Override
public void onBackPressed() {
if (!onBackStackFragment()) {
finish();
}
}
/**
* Should be returned to display fragments id of {@link android.view.ViewGroup}.
*
* @return resource id of {@link android.view.ViewGroup}.
*/
protected abstract
@IdRes
int fragmentLayoutId();
}
================================================
FILE: fragment/src/main/java/com/yanzhenjie/fragment/NoFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.view.SupportMenuInflater;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
/**
* Created by Yan Zhenjie on 2017/1/13.
*/
public class NoFragment extends Fragment {
public static final int RESULT_OK = Activity.RESULT_OK;
public static final int RESULT_CANCELED = Activity.RESULT_CANCELED;
private static final int REQUEST_CODE_INVALID = CompatActivity.REQUEST_CODE_INVALID;
/**
* Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.
*
* @param context context.
* @param fragmentClass class of fragment.
* @param subclass of {@link NoFragment}.
* @return new instance.
* @deprecated In {@code Activity} with {@link CompatActivity#fragment(Class)} instead;
* in the {@code Fragment} width {@link #fragment(Class)} instead.
*/
@Deprecated
public static T instantiate(Context context, Class fragmentClass) {
//noinspection unchecked
return (T) instantiate(context, fragmentClass.getName(), null);
}
/**
* Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.
*
* @param context context.
* @param fragmentClass class of fragment.
* @param bundle argument.
* @param subclass of {@link NoFragment}.
* @return new instance.
* @deprecated In {@code Activity} with {@link CompatActivity#fragment(Class, Bundle)} instead;
* in the {@code Fragment} width {@link #fragment(Class, Bundle)} instead.
*/
@Deprecated
public static T instantiate(Context context, Class fragmentClass, Bundle bundle) {
//noinspection unchecked
return (T) instantiate(context, fragmentClass.getName(), bundle);
}
/**
* Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.
*
* @param fragmentClass class of fragment.
* @param subclass of {@link NoFragment}.
* @return new instance.
*/
public final T fragment(Class fragmentClass) {
//noinspection unchecked
return (T) instantiate(getContext(), fragmentClass.getName(), null);
}
/**
* Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.
*
* @param fragmentClass class of fragment.
* @param bundle argument.
* @param subclass of {@link NoFragment}.
* @return new instance.
*/
public final T fragment(Class fragmentClass, Bundle bundle) {
//noinspection unchecked
return (T) instantiate(getContext(), fragmentClass.getName(), bundle);
}
/**
* Toolbar.
*/
private Toolbar mToolbar;
/**
* CompatActivity.
*/
private CompatActivity mActivity;
/**
* Get BaseActivity.
*
* @return {@link CompatActivity}.
*/
protected final CompatActivity getCompatActivity() {
return mActivity;
}
/**
* Start activity.
*
* @param clazz class for activity.
* @param {@link Activity}.
*/
protected final void startActivity(Class clazz) {
startActivity(new Intent(mActivity, clazz));
}
/**
* Start activity and finish my parent.
*
* @param clazz class for activity.
* @param {@link Activity}.
*/
protected final void startActivityFinish(Class clazz) {
startActivity(new Intent(mActivity, clazz));
mActivity.finish();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (CompatActivity) context;
}
/**
* Destroy me.
*/
public void finish() {
mActivity.onBackPressed();
}
/**
* Set Toolbar.
*
* @param toolbar {@link Toolbar}.
*/
public final void setToolbar(@NonNull Toolbar toolbar) {
this.mToolbar = toolbar;
onCreateOptionsMenu(mToolbar.getMenu(), new SupportMenuInflater(mActivity));
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
return onOptionsItemSelected(item);
}
});
}
/**
* Display home up button.
*
* @param drawableId drawable id.
*/
public final void displayHomeAsUpEnabled(@DrawableRes int drawableId) {
displayHomeAsUpEnabled(ContextCompat.getDrawable(mActivity, drawableId));
}
/**
* Display home up button.
*
* @param drawable {@link Drawable}.
*/
public final void displayHomeAsUpEnabled(Drawable drawable) {
mToolbar.setNavigationIcon(drawable);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!onInterceptToolbarBack())
finish();
}
});
}
/**
* Override this method, intercept backPressed of ToolBar.
*
* @return true, other wise false.
*/
public boolean onInterceptToolbarBack() {
return false;
}
/**
* Get Toolbar.
*
* @return {@link Toolbar}.
*/
protected final
@Nullable
Toolbar getToolbar() {
return mToolbar;
}
/**
* Set title.
*
* @param title title.
*/
protected void setTitle(CharSequence title) {
if (mToolbar != null)
mToolbar.setTitle(title);
}
/**
* Set title.
*
* @param titleId string resource id from {@code string.xml}.
*/
protected void setTitle(int titleId) {
if (mToolbar != null)
mToolbar.setTitle(titleId);
}
/**
* Set sub title.
*
* @param title sub title.
*/
protected void setSubtitle(CharSequence title) {
if (mToolbar != null)
mToolbar.setSubtitle(title);
}
/**
* Set sub title.
*
* @param titleId string resource id from {@code string.xml}.
*/
protected void setSubtitle(int titleId) {
if (mToolbar != null)
mToolbar.setSubtitle(titleId);
}
// ------------------------- Stack ------------------------- //
/**
* Stack info.
*/
private CompatActivity.FragmentStackEntity mStackEntity;
/**
* Set result.
*
* @param resultCode result code, one of {@link NoFragment#RESULT_OK}, {@link NoFragment#RESULT_CANCELED}.
*/
protected final void setResult(@ResultCode int resultCode) {
mStackEntity.resultCode = resultCode;
}
/**
* Set result.
*
* @param resultCode resultCode, use {@link }.
* @param result {@link Bundle}.
*/
protected final void setResult(@ResultCode int resultCode, @NonNull Bundle result) {
mStackEntity.resultCode = resultCode;
mStackEntity.result = result;
}
/**
* Get the resultCode for requestCode.
*/
final void setStackEntity(@NonNull CompatActivity.FragmentStackEntity stackEntity) {
this.mStackEntity = stackEntity;
}
/**
* You should override it.
*
* @param resultCode resultCode.
* @param result {@link Bundle}.
*/
public void onFragmentResult(int requestCode, @ResultCode int resultCode, @Nullable Bundle result) {
}
/**
* Show a fragment.
*
* @param clazz fragment class.
* @param {@link NoFragment}.
*/
public final void startFragment(Class clazz) {
try {
NoFragment targetFragment = clazz.newInstance();
startFragment(targetFragment, true, REQUEST_CODE_INVALID);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a fragment.
*
* @param clazz fragment class.
* @param stickyStack sticky to back stack.
* @param {@link NoFragment}.
*/
public final void startFragment(Class clazz, boolean stickyStack) {
try {
NoFragment targetFragment = clazz.newInstance();
startFragment(targetFragment, stickyStack, REQUEST_CODE_INVALID);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a fragment.
*
* @param targetFragment fragment to display.
* @param {@link NoFragment}.
*/
public final void startFragment(T targetFragment) {
startFragment(targetFragment, true, REQUEST_CODE_INVALID);
}
/**
* Show a fragment.
*
* @param targetFragment fragment to display.
* @param stickyStack sticky back stack.
* @param {@link NoFragment}.
*/
public final void startFragment(T targetFragment, boolean stickyStack) {
startFragment(targetFragment, stickyStack, REQUEST_CODE_INVALID);
}
/**
* Show a fragment for result.
*
* @param clazz fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
* @deprecated use {@link #startFragmentForResult(Class, int)} instead.
*/
@Deprecated
public final void startFragmentForResquest(Class clazz, int requestCode) {
startFragmentForResult(clazz, requestCode);
}
/**
* Show a fragment for result.
*
* @param targetFragment fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
* @deprecated use {@link #startFragmentForResult(Class, int)} instead.
*/
@Deprecated
public final void startFragmentForResquest(T targetFragment, int requestCode) {
startFragmentForResult(targetFragment, requestCode);
}
/**
* Show a fragment for result.
*
* @param clazz fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
*/
public final void startFragmentForResult(Class clazz, int requestCode) {
try {
NoFragment targetFragment = clazz.newInstance();
startFragment(targetFragment, true, requestCode);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a fragment for result.
*
* @param targetFragment fragment to display.
* @param requestCode requestCode.
* @param {@link NoFragment}.
*/
public final void startFragmentForResult(T targetFragment, int requestCode) {
startFragment(targetFragment, true, requestCode);
}
/**
* Show a fragment.
*
* @param targetFragment fragment to display.
* @param stickyStack sticky back stack.
* @param requestCode requestCode.
* @param {@link NoFragment}.
*/
private void startFragment(T targetFragment, boolean stickyStack, int requestCode) {
mActivity.startFragment(this, targetFragment, stickyStack, requestCode);
}
}
================================================
FILE: fragment/src/main/java/com/yanzhenjie/fragment/ResultCode.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment;
import android.support.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
@IntDef({NoFragment.RESULT_OK, NoFragment.RESULT_CANCELED})
@Retention(RetentionPolicy.SOURCE)
public @interface ResultCode {
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Fri Apr 21 14:20:40 CST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
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: sample/build.gradle
================================================
apply plugin: rootProject.ext.plugins.application
android {
compileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion
defaultConfig {
applicationId rootProject.ext.android.applicationId
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
jackOptions {
enabled true
}
}
}
dependencies {
compile rootProject.ext.dependencies.design
compile rootProject.ext.dependencies.fragment
compile rootProject.ext.dependencies.alertdialog
}
================================================
FILE: sample/src/main/AndroidManifest.xml
================================================
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/MainActivity.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample;
import android.os.Bundle;
import com.yanzhenjie.fragment.CompatActivity;
import com.yanzhenjie.fragment.sample.fragment.MainFragment;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class MainActivity extends CompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* 继承CompatActivity后,显示一个fragment就这么简单,不要怀疑自己的眼睛,这是真的。
*/
startFragment(MainFragment.class);
}
@Override
protected int fragmentLayoutId() {
return R.id.fragment_root;
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/adapter/RecyclerAdapter.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yanzhenjie.fragment.sample.R;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter {
private LayoutInflater mLayoutInflater;
private int itemCount;
public RecyclerAdapter(Context context, int itemCount) {
mLayoutInflater = LayoutInflater.from(context);
this.itemCount = itemCount;
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ItemViewHolder(mLayoutInflater.inflate(R.layout.item, parent, false));
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return itemCount;
}
static class ItemViewHolder extends RecyclerView.ViewHolder {
public ItemViewHolder(View itemView) {
super(itemView);
}
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/fragment/ArgumentFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.yanzhenjie.fragment.NoFragment;
import com.yanzhenjie.fragment.sample.R;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class ArgumentFragment extends NoFragment {
private Toolbar mToolbar;
private TextView mTvMessage;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_argument, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mTvMessage = (TextView) view.findViewById(R.id.tv_message);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setToolbar(mToolbar);
setTitle(R.string.title_fragment_argument);
displayHomeAsUpEnabled(R.drawable.ic_close_white);
Bundle bundle = getArguments();
String message = bundle.getString("hehe") + "\r\n";
message += bundle.getString("meng") + "\r\n";
message += bundle.getString("bang") + "\r\n";
message += bundle.getString("meme") + "\r\n";
mTvMessage.setText(message);
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/fragment/MainFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.fragment.NoFragment;
import com.yanzhenjie.fragment.sample.R;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class MainFragment extends NoFragment implements View.OnClickListener {
private Toolbar mToolbar;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
view.findViewById(R.id.btn_menu_more).setOnClickListener(this);
view.findViewById(R.id.btn_argument).setOnClickListener(this);
view.findViewById(R.id.btn_for_result).setOnClickListener(this);
view.findViewById(R.id.btn_stack).setOnClickListener(this);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// First must set toolbar, will invoke: onCreateOptionsMenu();
setToolbar(mToolbar);
// Set title for toolbar:
setTitle(R.string.title_fragment_main);
// Display close button.
displayHomeAsUpEnabled(R.drawable.ic_close_white);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_menu_more: {
startFragment(MoreMenuFragment.class);
break;
}
case R.id.btn_for_result: {
startFragmentForResquest(StartResultFragment.class, 100);
break;
}
case R.id.btn_argument: {
Bundle bundle = new Bundle();
bundle.putString("hehe", "呵呵哒");
bundle.putString("meng", "萌萌哒");
bundle.putString("bang", "棒棒哒");
bundle.putString("meme", "么么哒");
// Create fragment_menu for bundle.
NoFragment fragment = fragment(ArgumentFragment.class, bundle);
startFragment(fragment);
break;
}
case R.id.btn_stack: {
// Second argument false: don't join the back stack.
startFragment(StackFragment.class, false);
break;
}
}
}
@Override
public void onFragmentResult(int requestCode, int resultCode, @Nullable Bundle result) {
switch (requestCode) {
case 100: {
if (resultCode == RESULT_OK) {
String message = result.getString("message");
AlertDialog.build(getContext())
.setCancelable(true)
.setTitle(R.string.result)
.setMessage(message)
.setPositiveButton(R.string.ok, (dialog, which) -> {
// TODO nothing.
})
.show();
} else if (resultCode == RESULT_CANCELED) {
Snackbar.make(mToolbar, R.string.message_canceled, Snackbar.LENGTH_SHORT).show();
}
break;
}
}
}
// ========================= Menu Sample ========================= //
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Load your menu.
inflater.inflate(R.menu.menu_fragment_main, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle menu item click.
int id = item.getItemId();
switch (id) {
case R.id.action_settings: {
Snackbar.make(mToolbar, R.string.action_settings, Snackbar.LENGTH_SHORT).show();
break;
}
case R.id.action_exit: {
Snackbar.make(mToolbar, R.string.action_exit, Snackbar.LENGTH_SHORT).show();
break;
}
}
return true;
}
// ========================= Close Button ========================= //
@Override
public boolean onInterceptToolbarBack() {
// Intercept close button click event.
Snackbar.make(mToolbar, R.string.intercept_close, Snackbar.LENGTH_SHORT).show();
return true;
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/fragment/MoreMenuFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.yanzhenjie.fragment.NoFragment;
import com.yanzhenjie.fragment.sample.R;
import com.yanzhenjie.fragment.sample.adapter.RecyclerAdapter;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class MoreMenuFragment extends NoFragment {
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_menu, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// First must set toolbar, will invoke: onCreateOptionsMenu();
setToolbar(mToolbar);
// Set title for toolbar:
setTitle(R.string.title_fragment_setting);
// Display close button.
displayHomeAsUpEnabled(R.drawable.ic_back_white);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(new RecyclerAdapter(getContext(), 100));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Load your menu.
inflater.inflate(R.menu.menu_fragment_setting, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle menu item click.
int id = item.getItemId();
switch (id) {
case R.id.action_add_friend: {
Snackbar.make(mRecyclerView, R.string.action_add_friend, Snackbar.LENGTH_SHORT).show();
break;
}
case R.id.action_satisfied: {
Snackbar.make(mRecyclerView, R.string.action_satisfied, Snackbar.LENGTH_SHORT).show();
break;
}
case R.id.action_dissatisfied: {
Snackbar.make(mRecyclerView, R.string.action_dissatisfied, Snackbar.LENGTH_SHORT).show();
break;
}
case R.id.action_neutral: {
Snackbar.make(mRecyclerView, R.string.action_neutral, Snackbar.LENGTH_SHORT).show();
break;
}
}
return true;
}
@Override
public boolean onInterceptToolbarBack() {
Toast.makeText(getContext(), R.string.no_intercept_close, Toast.LENGTH_SHORT).show();
return false;
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/fragment/StackFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.yanzhenjie.fragment.NoFragment;
import com.yanzhenjie.fragment.sample.R;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class StackFragment extends NoFragment {
private Toolbar mToolbar;
private Button mBtnGo;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_stack, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mBtnGo = (Button) view.findViewById(R.id.btn_go);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setToolbar(mToolbar);
setTitle(R.string.title_fragment_stack);
displayHomeAsUpEnabled(R.drawable.ic_back_white);
mBtnGo.setOnClickListener(v -> startFragment(StackNewFragment.class));
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/fragment/StackNewFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.yanzhenjie.fragment.NoFragment;
import com.yanzhenjie.fragment.sample.R;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class StackNewFragment extends NoFragment {
private Toolbar mToolbar;
private Button mBtnBack;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_stack_new, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mBtnBack = (Button) view.findViewById(R.id.btn_back);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setToolbar(mToolbar);
setTitle(R.string.title_fragment_stack_new);
displayHomeAsUpEnabled(R.drawable.ic_back_white);
mBtnBack.setOnClickListener(v -> finish());
}
}
================================================
FILE: sample/src/main/java/com/yanzhenjie/fragment/sample/fragment/StartResultFragment.java
================================================
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.fragment.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.yanzhenjie.fragment.NoFragment;
import com.yanzhenjie.fragment.sample.R;
/**
* Created by Yan Zhenjie on 2017/1/15.
*/
public class StartResultFragment extends NoFragment {
private Toolbar mToolbar;
private EditText mEditText;
private Button mBtnBack;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_result, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mEditText = (EditText) view.findViewById(R.id.edit);
mBtnBack = (Button) view.findViewById(R.id.btn_back);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setToolbar(mToolbar);
displayHomeAsUpEnabled(R.drawable.ic_back_white);
setTitle(R.string.title_fragment_result);
mBtnBack.setOnClickListener(v -> {
String result = mEditText.getText().toString();
if (TextUtils.isEmpty(result)) {
result = getString(R.string.message_null);
}
Bundle bundle = new Bundle();
bundle.putString("message", result);
setResult(RESULT_OK, bundle);
finish();
});
}
}
================================================
FILE: sample/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragment_argument.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragment_main.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragment_menu.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragment_result.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragment_stack.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragment_stack_new.xml
================================================
================================================
FILE: sample/src/main/res/layout/item.xml
================================================
================================================
FILE: sample/src/main/res/menu/menu_fragment_main.xml
================================================
================================================
FILE: sample/src/main/res/menu/menu_fragment_setting.xml
================================================
================================================
FILE: sample/src/main/res/values/colors.xml
================================================
#3F51B5
#303F9F
#FF4081
================================================
FILE: sample/src/main/res/values/dimens.xml
================================================
10dp
10dp
10dp
10dp
10dp
16sp
18sp
================================================
FILE: sample/src/main/res/values/strings.xml
================================================
NoFragment
好的
MainFragment
溢出菜单
传参数
StartFragmentForResult
不保存回退栈
我是标题
我是内容
拦截关闭按钮点击事件
设置
退出
MoreMenuFragment
不拦截关闭
添加
心情
开心
难过
一般
ArgumentFragment
StartResultFragment
结果
返回数据
返回
取消了操作
您没有填写返回内容
StackFragment
打开新的Fragment
等下返回的时候看不到我了就。
StackNewFragment
返回的时候看不到调用我的页面。
================================================
FILE: sample/src/main/res/values/styles.xml
================================================
================================================
FILE: settings.gradle
================================================
include ':sample', ':fragment'