Compare commits

...

109 Commits

Author SHA1 Message Date
Eric Kuck 90f21d99a5 Version bump fix 2016-10-03 14:51:51 -05:00
Eric Kuck 641e0dc43c Version bump 2016-10-03 14:50:38 -05:00
Eric Kuck 91c993b005 Fixes #95 2016-10-03 14:36:41 -05:00
Eric Kuck 39ab4723ff Removes viewState getter and instead adds a controller subclass that can allows access to the saved view state and the time of view creation. 2016-10-03 14:11:00 -05:00
Eric Kuck 3769e706af Fixes #124 2016-10-03 14:05:03 -05:00
Yasuhiro Shimizu 26efe8f062 update to RxLifecycle 0.8.0, RxJava 1.2.0, RxAndroid 1.2.1 (#126) 2016-09-30 21:20:32 -05:00
Eric Kuck 8a890644ee Fixes issues with ControllerChangeHandlers being reused when they should not be. 2016-09-30 18:07:47 -05:00
Eric Kuck b2ffa7f7f6 Fixes #127 2016-09-30 17:38:14 -05:00
Eric Kuck 960b931744 Added a view state getter, which is needed if view state must be obtained at the time of view creation (ex: for Google Maps) 2016-09-30 17:33:54 -05:00
Eric Kuck 47158da05e Fixes tests 2016-09-28 13:16:56 -05:00
Eric Kuck b9c22d267d Fixed issue with no view being attached if orientation changed at the exact same instant as a SimpleSwapChangeHandler being run 2016-09-28 12:34:11 -05:00
Eric Kuck 46e6fac6db Fixed issue with AnimatorChangeHandler crashing if onAnimationEnd is called after onAnimationCancel 2016-09-27 15:57:37 -05:00
Eric Kuck dc68990bff Version bump 2016-09-26 10:32:23 -05:00
Eric Kuck e4f7e9e175 Fixes memory leak in CircularRevealAnimatorChangeHandler (and any other AnimatorChangeHandler that kept a reference to its view) 2016-09-26 09:50:29 -05:00
Eric Kuck 4ab99b68da Fixes #123 2016-09-26 09:34:41 -05:00
Eric Kuck b8bd64e078 Fixed leak in demo app 2016-09-26 09:24:32 -05:00
Eric Kuck 812d1f8911 Fixes issue where controllers that are being animated out, but haven't yet been detached, at the time of an orientation change could be incorrectly attached to the new Activity. 2016-09-24 11:24:13 -05:00
Eric Kuck ac8288fece Fixed issue where views would not detach when rapidly setting the root controller 2016-09-24 00:29:36 -05:00
Eric Kuck d2dd786b72 Fixed issue where setting the root controller twice in a row will cause the first controller's view to remain attached 2016-09-23 17:42:57 -05:00
Eric Kuck 7cf30b820c Travis yml fix 2016-09-06 16:44:45 -05:00
Eric Kuck 1120896438 Fixed some Leak Canary false-positives 2016-09-06 16:12:56 -05:00
Eric Kuck 093238cc52 Should fix #106 (more testing needed) 2016-09-06 16:10:47 -05:00
Eric Kuck c153e29273 Fixes #107 2016-09-06 15:49:30 -05:00
Eric Kuck 2757c7a4b6 Fixes #108 2016-09-06 15:46:25 -05:00
Eric Kuck 46091a7c99 Build tools update 2016-09-06 15:30:02 -05:00
Hannes Struß b0a5da2b82 Remove listeners after animator ends/is canceled (#104) 2016-09-05 10:43:22 -05:00
Adrian Pascu 0026566ba0 Nitpicks (#96)
* [Demo] Remove Butterknife unbinder from MainActivity

* Make deploy_snapshot.sh executable
2016-07-29 15:11:04 -05:00
dimsuz 9f640380bf Document a return value of Router.handleBack() (#93) 2016-07-20 17:49:59 -05:00
Eric Kuck a3faaede61 Fixes #97 and cleans up some tests 2016-07-20 15:41:19 -05:00
Eric Kuck 94d8add220 Fixes #98 2016-07-20 14:56:12 -05:00
Eric Kuck 6d4b5a5ef6 Version bump 2016-07-12 13:20:30 -05:00
Eric Kuck ae27c5e453 Another test for #86 2016-07-11 16:30:31 -05:00
Eric Kuck e4d23a7c74 Added some tests around #86 2016-07-11 16:24:07 -05:00
Eric Kuck 778cdcfd58 Controllers now properly persist their retain view modes 2016-07-11 13:37:38 -05:00
Eric Kuck 5e730947aa Corrected logic for first fix on #86 2016-07-11 13:37:22 -05:00
Eric Kuck 71b10c7365 Fixed back handling on child controllers demo 2016-07-08 15:08:05 -05:00
Eric Kuck 8c323b9613 Fixes issue with demo app trying to reuse change handlers 2016-07-08 14:59:19 -05:00
Eric Kuck af45aae110 Fixes 2nd issue associated with #86 2016-07-08 13:33:47 -05:00
Hannes Dorfmann d4c7e5791e Added oss sonatype snapshot url (#90) 2016-07-08 08:23:30 -05:00
Eric Kuck dc4c3a9709 Fixes at least one cause of #86 2016-07-07 20:59:37 -05:00
Eric Kuck ef84fbd547 AnimatorChangeHandlers are now properly cancelable 2016-07-07 18:32:04 -05:00
Eric Kuck 431569763e First pass at a fix for #85 2016-07-07 17:43:26 -05:00
Mykhailo Shchurov 7b5bab3681 Fixed typo in readme (#83) 2016-06-30 07:25:21 -05:00
Eric Kuck 86b32afdcb Fixed the build 2016-06-27 18:06:30 -05:00
Eric Kuck 557e4c2122 V2 (#80)
* Added test for adding and removing children

* [WIP] First pass at nested routers. Still needs a bunch of refactoring, testing, and documentation.

* Pulled save and restore calls out of the lifecycle, as Activity's callbacks make it impossible to fit into a nice little box (#48)

* [WIP] Removed old way of setting root controller in favor of reusing transactions

* [WIP] Added a bottom navigation demo for testing nested routers. Still have a bunch of issues with it.

* [WIP] Child routers now receive events properly (and don't crash most of the time!)

* Fixed a few leaks + handling of back presses in child routers

* Fixed tests

* Simplified making routers not handle back events

* Fixed onAttach callback for Android < 6

* Several child router bug fixes

* [WIP] Backstack getter and setter now exists (#64)

* Fixed some issues with viewpagers

* Added support for saving and restoring controllers in a pager adapter

* Fixed issue with re-attached child controllers prematurely destroying

* Better demo for multiple child routers + upgraded to butterknife 8

* Added basic master/detail flow demo

* Fixed issue where simultaneously pushing 2 controllers with animated transitions would cause the first controller's child routers to never re-load.

* Doc updates

* Removed ControllerTransaction base class, as everything is now added to routers.
Remove RouterTransaction.Builder and replaced it with a more fluent api

* Doc update

* Fixed tesets

* Doc update (had trouble with last version on maven central)

* Just some minor refactoring

* See ya, hungarian notation (#77)

* Should fix #75

* Adds public getters for RouterTransaction fields (#76)

* Doc updates

* Fixed #78 (deeply nested controllers not correctly restored)

* Fixes #79 (child routers no longer monitored after being restored)

* Final doc updates for v2
2016-06-27 17:57:50 -05:00
Matthew Haughton 8b29c1cd56 add link to javadoc.io from README (#72) 2016-06-24 16:30:43 -05:00
Mykhailo Shchurov 30ef5a187b Added cause to the instantiation exception (#62) 2016-06-11 16:01:10 -05:00
Mykhailo Shchurov ebe69bf98b Target Controller large bitmap issue fix 2016-06-06 13:14:56 -05:00
Mateusz Perlak a907263ab8 #57 - hiding keyboard onDetach (#58)
* hiding keyboard onDetach

* removed not needed isActive check
2016-06-06 13:14:33 -05:00
Eric Kuck 7528437f65 HorizontalChangeHandler now correctly resets the X translation. 2016-05-24 14:45:33 -07:00
adi1133 e2e8260876 Add proguard rules (#51)
* Add proguard rules

* Add default constructor to proguard rules
2016-05-16 15:35:16 -05:00
Eric Kuck 6dfc5839cc Fixed maven central artifacts 2016-05-12 10:36:54 -05:00
Eric Kuck 8cba63328f Travis should now ignore branches that don't need to be built yet [ci skip] 2016-05-11 17:12:55 -05:00
Eric Kuck 531cc3ff58 Version bump 2016-05-11 17:07:41 -05:00
Eric Kuck c7de32584b Fixed memory leak in view pager demo controller 2016-05-09 18:01:00 -05:00
Eric Kuck 625d1f15b6 Updated sonatype auth (#43) 2016-05-02 10:13:01 -05:00
Hannes Dorfmann 251fc42f67 Changed deploy_snaphsot permission (#41) 2016-04-29 09:58:25 -05:00
Hannes Dorfmann 0bf8e47c48 Fixing snapshot dependencies (#38)
* Resolving inner dependencies

* Resolving inner dependencies

* oops
2016-04-28 17:01:43 -05:00
Eric Kuck 7784f74102 Fixed artifact typo 2016-04-28 10:46:22 -05:00
Eric Kuck bfacab984b Added some tests for lifecycle call ordering 2016-04-27 15:45:59 -05:00
Eric Kuck f8a05731d9 Now removes the view's OnAttachStateListener before removing the reference
Fixes ordering of external lifecycle callbacks
2016-04-27 15:11:54 -05:00
Eric Kuck 116b5066c9 Fixed issue where view was not re-created if its old view was still attached. 2016-04-26 14:33:37 -05:00
Eric Kuck 011adca579 Fixed a typo 2016-04-25 13:33:36 -05:00
adi1133 95de69a006 Make getControllerWithInstanceId search recursively (#30)
* Make getControllerWithInstanceId search recursively

* Deprecate getChildControllerWithInstanceId()

* Rename getControllerWithInstanceId to findController making it internal
2016-04-25 13:11:12 -05:00
Eric Kuck 6cea976d10 Added info about snapshot builds to readme 2016-04-19 16:15:39 -05:00
Eric Kuck c573a8961c fixed conflict 2016-04-19 16:07:12 -05:00
Eric Kuck 6c444fecfb Added nexus details to travis.yml 2016-04-19 15:59:20 -05:00
Eric Kuck 29d1fd1c7d Switched to sonatype for deployment + snapshots 2016-04-19 15:52:40 -05:00
Eric Kuck f6493507f4 Options menu now works for child controllers
Added more tests
2016-04-18 14:07:52 -05:00
Eric Kuck b012df262d Dependency version update 2016-04-16 14:35:39 -05:00
Eric Kuck e028ed42da Version bump 2016-04-16 14:22:38 -05:00
Eric Kuck 43dc561ac2 Fixed up some save/restore view state stuff (incl. tests) 2016-04-16 13:51:37 -05:00
Eric Kuck 217b55090a Added test for backgrounding the host activity 2016-04-16 13:18:24 -05:00
Eric Kuck 5c8b78e41d Fixed orientation change test 2016-04-16 12:25:45 -05:00
Eric Kuck 899dd70d50 Merge pull request #25 from sockeqwe/viewStateListener
added methods to lifecyclelistener for saving/restoring viewstate
2016-04-16 12:04:51 -05:00
Eric Kuck d945571d31 Improved controller lifecycle test coverage (and clarity) 2016-04-16 12:04:20 -05:00
Hannes Dorfmann b7a4386d22 Renamed parameter of onRestoreViewState() to savedViewState 2016-04-16 14:01:41 +02:00
Hannes Dorfmann b117307340 added methods to lifecyclelistener for saving/restoring viewstate 2016-04-15 19:52:43 +02:00
Eric Kuck b8ccf3623f Fixed onRestoreState call ordering for controllers with parent/child relationships 2016-04-14 14:20:56 -05:00
Eric Kuck 495145b72b Router, Activity, target controller, etc is all now available in onRestoreInstanceState 2016-04-13 15:39:09 -05:00
Eric Kuck 99e25d65f2 Merge pull request #20 from adi1133/develop
Fix crash caused by recreating static nested classes using reflection
2016-04-12 16:41:05 -05:00
Adi Pascu 2619d13c8d Fix crash caused by recreating static nested classes using reflection 2016-04-12 23:49:10 +03:00
Eric Kuck 62a5a81107 Fixed typo 2016-04-12 14:33:03 -05:00
Eric Kuck d234dd4c75 Added external onActivityResult method to Controllers (for use with things like the Facebook SDK)
Removed CircularRevealChangeHandler from the core project
2016-04-12 14:18:01 -05:00
Eric Kuck a48b49cdbe All demos should now run on API < 21 2016-04-06 12:07:51 -05:00
Eric Kuck f0a488c711 Added options menu support for controllers
Updated demo app to have a toolbar
2016-04-05 13:34:14 -05:00
Eric Kuck 511c229364 Fixed issue with re-attaching when the host Activity never left with window 2016-04-04 23:23:01 -05:00
Eric Kuck b5d0e46740 Now enforces only setting a controller's target one time. 2016-04-04 17:45:29 -05:00
Eric Kuck 8f1be7fe21 Updated readme to reflect latest lifecycle updates 2016-04-04 17:29:22 -05:00
Eric Kuck 8a70c09fea Big lifecycle update + a few bug fixes 2016-04-04 17:03:43 -05:00
Eric Kuck 343e8c92e5 Merge pull request #9 from ravidsrk/patch-1
Added code syntax highlighting to Readme
2016-04-01 06:49:14 -05:00
Ravindra Kumar 332788ee01 Added code syntax highlighting to Readme 2016-04-01 00:51:53 -04:00
Eric Kuck acf77101a7 Merge pull request #4 from sockeqwe/patch-1
Conductor class final; added private Constructor
2016-03-31 18:29:21 -05:00
Hannes Dorfmann cba372966d Conductor class final; added private Constructor 2016-04-01 00:32:04 +02:00
Eric Kuck fff9f76e8a Version bump 2016-03-31 14:12:23 -05:00
Eric Kuck bcc8f47856 Fixed tests to work with corrected lifecycle 2016-03-30 18:35:52 -05:00
Eric Kuck 61d68a9c6c Tweaks to ensure lifecycle callback chain remains intact when the activity is destroyed unexpectedly 2016-03-30 18:32:05 -05:00
Eric Kuck 5e7258973e Tweaks to ensure lifecycle callback chain remains intact when the activity is destroyed unexpectedly 2016-03-30 18:30:23 -05:00
Eric Kuck 194696e9cb Added a method for animating setting the root controller 2016-03-30 12:43:13 -05:00
Eric Kuck 5130909efc Fixed readme's controller implementation 2016-03-28 22:30:43 -05:00
Eric Kuck 7874c4f72d Typo fix 2016-03-26 19:21:42 -05:00
Eric Kuck 8399868a63 Minor lifecycle bug fixes 2016-03-26 19:19:02 -05:00
Eric Kuck 3e97e7f8a8 Minor demo app cleanup 2016-03-23 09:27:36 -05:00
Eric Kuck d5e54f33a0 Fixed issue with screen rotation 2016-03-22 14:42:31 -05:00
Eric Kuck 58d1f37db0 Test fix 2016-03-21 22:35:51 -05:00
Eric Kuck 7c175e4ce5 Fixed where the Controller's view is set internally 2016-03-21 22:30:56 -05:00
Eric Kuck 328b8a0873 Readme update 2016-03-21 11:55:46 -05:00
Eric Kuck db446279bb Added some basic lint checks 2016-03-21 11:30:13 -05:00
Eric Kuck 80042ea71d Minor demo app refactor 2016-03-20 00:04:22 -05:00
112 changed files with 5590 additions and 1844 deletions
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
#
# Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo.
#
# Adapted from https://coderwall.com/p/9b_lfq and
# http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/
SLUG="bluelinelabs/Conductor"
JDK="oraclejdk8"
BRANCH="develop"
set -e
if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then
echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'."
elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then
echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'."
elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
echo "Skipping snapshot deployment: was pull request."
elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then
echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'."
else
echo "Deploying snapshot..."
./gradlew clean uploadArchives
echo "Snapshot deployed!"
fi
-1
View File
@@ -15,7 +15,6 @@ gen-external-apklibs
# Gradle
.gradle
build
gradle.properties
# Maven
target
+22
View File
@@ -9,3 +9,25 @@ android:
script:
- ./gradlew test
jdk:
- oraclejdk8
branches:
only:
- develop
- master
after_success:
- .buildscript/deploy_snapshot.sh
cache:
directories:
- $HOME/.gradle
sudo: false
env:
global:
- secure: SoRbxmNTxnGY9qPR5Z8HraRLhHrq7eJ2UaHMuiXDSxpLwUI0IMw+8+l59PNdy/C5ZXXrr6jo6cj+sn/4u6VNg74e2h9i//O+kYGvbGJUnBx8uo1INOrVenpzSnIgxbRLxyN3ZDp8YgwJMl8MSCLM1nj2OMzjNRY5EBnEw5h3qNXBs4Hyhpp2FxVk7dA2yLMUZdOpFKJIsqhH1ZHnCEnYrLlx5cVM9yoefFmJ3PptgumtV8ciBnp0lgDGy5nTykPh6zJBz4rAXgOr95WHvoqpyBRAUZIUEgw/vB5aF8/g+CX2gvTlJYF2N9LgJTNHMEwd+zJtmjM8JzkuCfTT3uMDD3JK5O8eNU03a/+9AkbKpK2+Pt829ZPdkObavXi+oJykCmD5IirukVXE9ushR2J+fM4VOvJinsANSI0zjzFpjZMplX63lfhNu/4lj3AWV2G4rkZd3vZQU+4AuhGQ469RA9BFqUJDIsiQQJwHEAWIqo9WNi6H4H8OhferACd2T3d5Y0O3s0EG5JfdADBPh9YDIkB2zEtGc3gGdxFzxVmH48BJViubAHlH4SgJn7gn69T9wyKmJ1M8F9ph/CdhSHT3kADRDELPEEVXCcANG/verCbyxMlAMXvLNKIGgHD+A0/z9QS1WduOOZwWd1mAuNuEg/rq2OB8SoDTv/BseHrXOpc=
- secure: WpqrbdAvNUFn5cM/Iu3zJOaDvT3jWGHCRwvxQCzX9F8iJeTggB5dB2rjgUDCx8LJ8UAt0VCeOcGtR1RT3EHyaHorN3NWeLcBFAHSz2sXv+2xGkspsXwjfygghZTCdYEzhhvmWlz9Ln4s4QJ2fBFZA07pG0jw4Cp1hSQiJ1WlKfDQezldj8D3pPwg1oOq4b5+HVucQ6+PPVwzGk2c3etwb5205L8H8flRjZrP95mFa5n/H3b/HFIsKX5p+CPNIKCrjBEmX0nHXiV0+g6lBQBV1iCwT56vfmN8Urm4KLId71iMpmvstDxlBBRQx3sz41vxIWGFn/oN7iXJI6XfzVFkyvrd9XAQLQFffq4KpN0REy1L3rjO46sYRXu1ycCP5VFVAAwKZn+o1q6xRjCuma2Qj4tqY754pwPNyzXnndFLO7hoN8KjOgV2nk75+XlRG8LhP356CHET62QBZgJ+sl+aFM3hhknsaEuDQywo8Uz4WZL0lPmYqm5BImQT9sTEF6uQNofg4gMy/uqgGhpLtseQW3PoJXB6dmD5JdNxlOalkGSQ+aI/q5QvR6ruIiuap66o4Bu+YTvHiS2hVzmldvMmLFsU1/zECSI6Fs/vkwRN55R9mbPROWi8SzvftYk9shkFMC5QC1FXA/CHqX1W5nl/HpMrs8R9uPhdZ1lifCiW8Rk=
+41 -27
View File
@@ -1,4 +1,4 @@
[![Travis Build](https://travis-ci.org/bluelinelabs/Conductor.svg)](https://travis-ci.org/bluelinelabs/Conductor)
[![Travis Build](https://travis-ci.org/bluelinelabs/Conductor.svg)](https://travis-ci.org/bluelinelabs/Conductor) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Conductor-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/3361) [![Javadocs](http://javadoc.io/badge/com.bluelinelabs/conductor.svg)](http://javadoc.io/doc/com.bluelinelabs/conductor)
# Conductor
@@ -14,20 +14,39 @@ A small, yet full-featured framework that allows building View-based Android app
:floppy_disk: | State persistence
:phone: | Callbacks for onActivityResult, onRequestPermissionsResult, etc
:european_post_office: | MVP / MVVM / VIPER / MVC ready
Conductor is architecture-agnostic and does not try to force any design decisions on the developer. We here at BlueLine Labs tend to use either MVP or MVVM, but it would work equally well with standard MVC or whatever else you want to throw at it.
## Installation
```gradle
compile 'com.bluelinelabs:conductor:1.0.2'
compile 'com.bluelinelabs:conductor:2.0.3'
// If you want the components that go along with
// Android's support libraries (currently just a PagerAdapter):
compile 'com.bluelinelabs:conductor-support:1.0.2'
compile 'com.bluelinelabs:conductor-support:2.0.3'
// If you want RxJava/RxAndroid lifecycle support:
compile 'com.bluelinelabs:conductor-rxlifecycle:1.0.2'
compile 'com.bluelinelabs:conductor-rxlifecycle:2.0.3'
```
SNAPSHOT:
```gradle
compile 'com.bluelinelabs:conductor:2.0.4-SNAPSHOT'
compile 'com.bluelinelabs:conductor-support:2.0.4-SNAPSHOT'
compile 'com.bluelinelabs:conductor-rxlifecycle:2.0.4-SNAPSHOT'
```
You also have to add the url to the snapshot repository:
```gradle
allprojects {
repositories {
...
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
```
## Components to Know
@@ -43,28 +62,28 @@ __ControllerTransaction__ | Transactions are used to define data about adding Co
### Minimal Activity implementation
```
```java
public class MainActivity extends Activity {
private Router mRouter;
private Router router;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup container = (ViewGroup)findViewById(R.id.controller_container)
mRouter = Conductor.attachRouter(this, container, savedInstanceState);
if (!mRouter.hasRootController()) {
mRouter.setRoot(new HomeController());
ViewGroup container = (ViewGroup)findViewById(R.id.controller_container);
router = Conductor.attachRouter(this, container, savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new HomeController()));
}
}
@Override
public void onBackPressed() {
if (!mRouter.handleBack()) {
if (!router.handleBack()) {
super.onBackPressed();
}
}
@@ -74,19 +93,14 @@ public class MainActivity extends Activity {
### Minimal Controller implementation
```
```java
public class HomeController extends Controller {
@Override
protected int layoutId() {
return R.layout.controller_overlay;
}
@Override
public void onBindView(@NonNull View view) {
super.onBindView(view);
((TextView)view.findViewById(R.id.tv_title)).setText("Hello World");
protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
View view = inflater.inflate(R.layout.controller_home, container, false);
((TextView)view.findViewById(R.id.tv_title)).setText("Hello World");
return view;
}
}
@@ -110,11 +124,11 @@ The lifecycle of a Controller is significantly simpler to understand than that o
### Custom Change Handlers
`ControllerChangeHandler` can be subclassed in order to perform different functions when changing between two `Controllers`. Two convenience `ControllerChangeHandler` subclasses are included to cover most basic needs: `AnimatorChangeHandler`, which will use an `Animator` object to transition between two views, and `TransitionChangeHandler`, which will use Lollipop's `Transition` framework for transitioning between views.
### Child Controllers
`addChildController` can be called on a `Controller` in order to add nested `Controller`s. Child `Controller`s will receive all lifecycle callbacks that parents get.
### Child Routers & Controllers
`getChildRouter` can be called on a `Controller` in order to get a nested `Router` into which child `Controller`s can be pushed. This enables creating advanced layouts, such as Master/Detail.
### RxJava Lifecycle
If the RxLifecycle dependency has been added, there is an `RxController` available that can be used along with the standard [RxLifecycle library](https://github.com/trello/RxLifecycle). There is also a `ControllerLifecycleProvider` available if you do not wish to use this subclass.
If the RxLifecycle dependency has been added, there is an `RxController` available that can be used along with the standard [RxLifecycle library](https://github.com/trello/RxLifecycle). There is also a `ControllerLifecycleProvider` available if you do not wish to use this subclass.
## License
```
-101
View File
@@ -1,101 +0,0 @@
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'
group = 'com.bluelinelabs'
version = rootProject.ext.versionName
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))
exclude '**/R.java'
exclude '**/internal/**'
failOnError = false
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar
archives sourcesJar
}
if (project.hasProperty('pom_name')) {
install {
repositories.mavenInstaller {
pom.project {
name pom_name
description pom_description
url pom_url
packaging pom_packaging
groupId 'com.bluelinelabs'
artifactId project.hasProperty('artifactId') ? project.ext.artifactId : ''
organization {
name 'BlueLine Labs'
url 'http://bluelinelabs.com'
}
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
scm {
url pom_url
connection pom_git_connection
developerConnection pom_git_connection
}
developers {
developer {
id 'erickuck'
name 'Eric Kuck'
}
}
}
}
}
bintray {
user = project.hasProperty('bintray_username') ? bintray_username : ''
key = project.hasProperty('bintray_api_key') ? bintray_api_key : ''
configurations = ['archives']
dryRun = false
publish = false
pkg {
repo = 'bluelinelabs'
userOrg = 'bluelinelabs'
name = pom_name
desc = pom_description
websiteUrl = pom_url
issueTrackerUrl = pom_issue_tracker_url
vcsUrl = pom_url
licenses = ['Apache-2.0']
labels = pom_labels
version {
name = project.version
gpg {
sign = true
passphrase = project.hasProperty('bintray_gpg_passphrase') ? bintray_gpg_passphrase : ''
}
mavenCentralSync {
sync = false
user = project.hasProperty('maven_central_username') ? maven_central_username : ''
password = project.hasProperty('maven_central_password') ? maven_central_password : ''
close = '1'
}
}
}
}
}
+1 -6
View File
@@ -3,15 +3,10 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
classpath 'com.android.tools.build:gradle:2.2.0'
}
}
plugins {
id "com.jfrog.bintray" version "1.5"
}
allprojects {
repositories {
jcenter()
+20
View File
@@ -0,0 +1,20 @@
apply plugin: 'java'
configurations {
lintChecks
}
dependencies {
compile rootProject.ext.lintapi
compile rootProject.ext.lintchecks
lintChecks files(jar)
}
jar {
manifest {
attributes('Lint-Registry': 'com.bluelinelabs.conductor.lint.IssueRegistry')
}
}
apply from: rootProject.file('dependencies.gradle')
@@ -0,0 +1,100 @@
package com.bluelinelabs.conductor.lint;
import com.android.annotations.NonNull;
import com.android.tools.lint.client.api.JavaParser.ResolvedClass;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.Speed;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;
import lombok.ast.ClassDeclaration;
import lombok.ast.ConstructorDeclaration;
import lombok.ast.Node;
import lombok.ast.NormalTypeBody;
import lombok.ast.StrictListAccessor;
import lombok.ast.TypeMember;
import lombok.ast.VariableDefinition;
public final class ControllerChangeHandlerIssueDetector extends Detector implements Detector.JavaScanner, Detector.ClassScanner {
public static final Issue ISSUE =
Issue.create("ValidControllerChangeHandler", "ControllerChangeHandler not instantiatable",
"Non-abstract ControllerChangeHandler instances must have a default constructor for the"
+ " system to re-create them in the case of the process being killed.",
Category.CORRECTNESS, 6, Severity.FATAL,
new Implementation(ControllerChangeHandlerIssueDetector.class, Scope.JAVA_FILE_SCOPE));
public ControllerChangeHandlerIssueDetector() { }
@NonNull
@Override
public Speed getSpeed() {
return Speed.FAST;
}
@Override
public List<String> applicableSuperClasses() {
return Collections.singletonList("com.bluelinelabs.conductor.ControllerChangeHandler");
}
@Override
public void checkClass(@NonNull JavaContext context, ClassDeclaration node,
@NonNull Node declarationOrAnonymous, @NonNull ResolvedClass cls) {
if (node == null) {
return;
}
final int flags = node.astModifiers().getEffectiveModifierFlags();
if ((flags & Modifier.ABSTRACT) != 0) {
return;
}
if ((flags & Modifier.PUBLIC) == 0) {
String message = String.format("This ControllerChangeHandler class should be public (%1$s)", cls.getName());
context.report(ISSUE, node, context.getLocation(node.astName()), message);
return;
}
if (cls.getContainingClass() != null && (flags & Modifier.STATIC) == 0) {
String message = String.format("This ControllerChangeHandler inner class should be static (%1$s)", cls.getName());
context.report(ISSUE, node, context.getLocation(node.astName()), message);
return;
}
boolean hasConstructor = false;
boolean hasDefaultConstructor = false;
NormalTypeBody body = node.astBody();
if (body != null) {
for (TypeMember member : body.astMembers()) {
if (member instanceof ConstructorDeclaration) {
hasConstructor = true;
ConstructorDeclaration constructor = (ConstructorDeclaration)member;
if (constructor.astModifiers().isPublic()) {
StrictListAccessor<VariableDefinition, ConstructorDeclaration> params = constructor.astParameters();
if (params.isEmpty()) {
hasDefaultConstructor = true;
break;
}
}
}
}
}
if (hasConstructor && !hasDefaultConstructor) {
String message = String.format(
"This ControllerChangeHandler needs to have a public default constructor (`%1$s`)",
cls.getName());
context.report(ISSUE, node, context.getLocation(node.astName()), message);
}
}
}
@@ -0,0 +1,108 @@
package com.bluelinelabs.conductor.lint;
import com.android.SdkConstants;
import com.android.annotations.NonNull;
import com.android.tools.lint.client.api.JavaParser.ResolvedClass;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.Speed;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;
import lombok.ast.ClassDeclaration;
import lombok.ast.ConstructorDeclaration;
import lombok.ast.Node;
import lombok.ast.NormalTypeBody;
import lombok.ast.StrictListAccessor;
import lombok.ast.TypeMember;
import lombok.ast.VariableDefinition;
public final class ControllerIssueDetector extends Detector implements Detector.JavaScanner, Detector.ClassScanner {
public static final Issue ISSUE =
Issue.create("ValidController", "Controller not instantiatable",
"Non-abstract Controller instances must have a default or single-argument constructor"
+ " that takes a Bundle in order for the system to re-create them in the"
+ " case of the process being killed.", Category.CORRECTNESS, 6, Severity.FATAL,
new Implementation(ControllerIssueDetector.class, Scope.JAVA_FILE_SCOPE));
public ControllerIssueDetector() { }
@NonNull
@Override
public Speed getSpeed() {
return Speed.FAST;
}
@Override
public List<String> applicableSuperClasses() {
return Collections.singletonList("com.bluelinelabs.conductor.Controller");
}
@Override
public void checkClass(@NonNull JavaContext context, ClassDeclaration node,
@NonNull Node declarationOrAnonymous, @NonNull ResolvedClass cls) {
if (node == null) {
return;
}
final int flags = node.astModifiers().getEffectiveModifierFlags();
if ((flags & Modifier.ABSTRACT) != 0) {
return;
}
if ((flags & Modifier.PUBLIC) == 0) {
String message = String.format("This Controller class should be public (%1$s)", cls.getName());
context.report(ISSUE, node, context.getLocation(node.astName()), message);
return;
}
if (cls.getContainingClass() != null && (flags & Modifier.STATIC) == 0) {
String message = String.format("This Controller inner class should be static (%1$s)", cls.getName());
context.report(ISSUE, node, context.getLocation(node.astName()), message);
return;
}
boolean hasConstructor = false;
boolean hasDefaultConstructor = false;
boolean hasBundleConstructor = false;
NormalTypeBody body = node.astBody();
if (body != null) {
for (TypeMember member : body.astMembers()) {
if (member instanceof ConstructorDeclaration) {
hasConstructor = true;
ConstructorDeclaration constructor = (ConstructorDeclaration)member;
if (constructor.astModifiers().isPublic()) {
StrictListAccessor<VariableDefinition, ConstructorDeclaration> params = constructor.astParameters();
if (params.isEmpty()) {
hasDefaultConstructor = true;
break;
} else if (params.size() == 1 &&
(params.first().astTypeReference().getTypeName().equals(SdkConstants.CLASS_BUNDLE)) ||
params.first().astTypeReference().getTypeName().equals("Bundle")) {
hasBundleConstructor = true;
break;
}
}
}
}
}
if (hasConstructor && !hasDefaultConstructor && !hasBundleConstructor) {
String message = String.format(
"This Controller needs to have either a public default constructor or a" +
" public single-argument constructor that takes a Bundle. (`%1$s`)",
cls.getName());
context.report(ISSUE, node, context.getLocation(node.astName()), message);
}
}
}
@@ -0,0 +1,14 @@
package com.bluelinelabs.conductor.lint;
import com.android.tools.lint.detector.api.Issue;
import java.util.Arrays;
import java.util.List;
public final class IssueRegistry extends com.android.tools.lint.client.api.IssueRegistry {
@Override public List<Issue> getIssues() {
return Arrays.asList(
ControllerIssueDetector.ISSUE,
ControllerChangeHandlerIssueDetector.ISSUE);
}
}
+6 -4
View File
@@ -1,3 +1,6 @@
apply from: rootProject.file('dependencies.gradle')
apply from: rootProject.file('gradle-mvn-push.gradle')
apply plugin: 'com.android.library'
android {
@@ -16,8 +19,8 @@ android {
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName
versionCode Integer.parseInt(project.VERSION_CODE)
versionName project.VERSION_NAME
}
}
@@ -25,11 +28,10 @@ dependencies {
compile rootProject.ext.rxJava
compile rootProject.ext.rxAndroid
compile rootProject.ext.rxLifecycle
compile rootProject.ext.rxLifecycleAndroid
compile project(':conductor')
}
ext.artifactId = 'conductor-rxlifecycle'
apply from: rootProject.file('dependencies.gradle')
apply from: rootProject.file('bll-gradle-push.gradle')
+3
View File
@@ -0,0 +1,3 @@
POM_NAME=Conductor RxLifecycle Extensions
POM_ARTIFACT_ID=conductor-rxlifecycle
POM_PACKAGING=aar
@@ -3,10 +3,10 @@ package com.bluelinelabs.conductor.rxlifecycle;
public enum ControllerEvent {
CREATE,
CREATE_VIEW,
ATTACH,
BIND_VIEW,
DETACH,
UNBIND_VIEW,
DESTROY_VIEW,
DESTROY
}
@@ -1,38 +0,0 @@
package com.bluelinelabs.conductor.rxlifecycle;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import rx.Observable;
/**
* Interface used for RxController. Can also be used if writing your own Controller component without subclassing RxController.
*/
public interface ControllerLifecycleProvider {
/**
* @return An observable that will have all {@link com.bluelinelabs.conductor.Controller} lifecycle events
*/
@NonNull
@CheckResult
Observable<ControllerEvent> lifecycle();
/**
* Will bind the source until a specific {@link ControllerEvent} occurs.
*
* @param event The {@link ControllerEvent} that should cause onComplete to be called
* @return A {@link rx.Observable.Transformer} that will call onComplete when the event occurs.
*/
@NonNull
@CheckResult
<T> Observable.Transformer<T, T> bindUntilEvent(@NonNull ControllerEvent event);
/**
* Will bind the source until the next reasonable {@link ControllerEvent} occurs.
* @return A {@link rx.Observable.Transformer} that will call onComplete when the event occurs.
*/
@NonNull
@CheckResult
<T> Observable.Transformer<T, T> bindToLifecycle();
}
@@ -21,8 +21,8 @@ public class ControllerLifecycleSubjectHelper {
controller.addLifecycleListener(new LifecycleListener() {
@Override
public void preBindView(@NonNull Controller controller, @NonNull View view) {
subject.onNext(ControllerEvent.BIND_VIEW);
public void preCreateView(@NonNull Controller controller) {
subject.onNext(ControllerEvent.CREATE_VIEW);
}
@Override
@@ -31,13 +31,13 @@ public class ControllerLifecycleSubjectHelper {
}
@Override
public void preUnbindView(@NonNull Controller controller, @NonNull View view) {
subject.onNext(ControllerEvent.UNBIND_VIEW);
public void preDetach(@NonNull Controller controller, @NonNull View view) {
subject.onNext(ControllerEvent.DETACH);
}
@Override
public void preDetach(@NonNull Controller controller, @NonNull View view) {
subject.onNext(ControllerEvent.DETACH);
public void preDestroyView(@NonNull Controller controller, @NonNull View view) {
subject.onNext(ControllerEvent.DESTROY_VIEW);
}
@Override
@@ -5,6 +5,8 @@ import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.bluelinelabs.conductor.Controller;
import com.trello.rxlifecycle.LifecycleProvider;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.RxLifecycle;
import rx.Observable;
@@ -13,9 +15,9 @@ import rx.subjects.BehaviorSubject;
/**
* A base {@link Controller} that can be used to expose lifecycle events using RxJava
*/
public abstract class RxController extends Controller implements ControllerLifecycleProvider {
public abstract class RxController extends Controller implements LifecycleProvider<ControllerEvent> {
private final BehaviorSubject<ControllerEvent> mLifecycleSubject;
private final BehaviorSubject<ControllerEvent> lifecycleSubject;
public RxController() {
this(null);
@@ -23,28 +25,28 @@ public abstract class RxController extends Controller implements ControllerLifec
public RxController(Bundle args) {
super(args);
mLifecycleSubject = ControllerLifecycleSubjectHelper.create(this);
lifecycleSubject = ControllerLifecycleSubjectHelper.create(this);
}
@Override
@NonNull
@CheckResult
public final Observable<ControllerEvent> lifecycle() {
return mLifecycleSubject.asObservable();
return lifecycleSubject.asObservable();
}
@Override
@NonNull
@CheckResult
public final <T> Observable.Transformer<T, T> bindUntilEvent(@NonNull ControllerEvent event) {
return RxLifecycle.bindUntilEvent(mLifecycleSubject, event);
public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ControllerEvent event) {
return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
}
@Override
@NonNull
@CheckResult
public final <T> Observable.Transformer<T, T> bindToLifecycle() {
return RxControllerLifecycle.bindController(mLifecycleSubject);
public final <T> LifecycleTransformer<T> bindToLifecycle() {
return RxControllerLifecycle.bindController(lifecycleSubject);
}
}
@@ -3,6 +3,7 @@ package com.bluelinelabs.conductor.rxlifecycle;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.OutsideLifecycleException;
import com.trello.rxlifecycle.RxLifecycle;
@@ -13,14 +14,14 @@ public class RxControllerLifecycle {
/**
* Binds the given source to a Controller lifecycle. This is the Controller version of
* {@link com.trello.rxlifecycle.RxLifecycle#bindFragment(Observable)}.
* {@link com.trello.rxlifecycle.android.RxLifecycleAndroid#bindFragment(Observable)}.
*
* @param lifecycle the lifecycle sequence of a Controller
* @return a reusable {@link Observable.Transformer} that unsubscribes the source during the Controller lifecycle
*/
@NonNull
@CheckResult
public static <T> Observable.Transformer<T, T> bindController(@NonNull final Observable<ControllerEvent> lifecycle) {
public static <T> LifecycleTransformer<T> bindController(@NonNull final Observable<ControllerEvent> lifecycle) {
return RxLifecycle.bind(lifecycle, CONTROLLER_LIFECYCLE);
}
@@ -33,8 +34,8 @@ public class RxControllerLifecycle {
return ControllerEvent.DESTROY;
case ATTACH:
return ControllerEvent.DETACH;
case BIND_VIEW:
return ControllerEvent.UNBIND_VIEW;
case CREATE_VIEW:
return ControllerEvent.DESTROY_VIEW;
case DETACH:
return ControllerEvent.DESTROY;
default:
+5 -4
View File
@@ -1,3 +1,6 @@
apply from: rootProject.file('dependencies.gradle')
apply from: rootProject.file('gradle-mvn-push.gradle')
apply plugin: 'com.android.library'
android {
@@ -16,8 +19,8 @@ android {
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName
versionCode Integer.parseInt(project.VERSION_CODE)
versionName project.VERSION_NAME
}
}
@@ -28,5 +31,3 @@ dependencies {
ext.artifactId = 'conductor-support'
apply from: rootProject.file('dependencies.gradle')
apply from: rootProject.file('bll-gradle-push.gradle')
+3
View File
@@ -0,0 +1,3 @@
POM_NAME=Conductor Support Extensions
POM_ARTIFACT_ID=conductor-support
POM_PACKAGING=aar
@@ -1,24 +1,34 @@
package com.bluelinelabs.conductor.support;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.ChildControllerTransaction;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
/**
* An adapter for ViewPagers that will handle adding and removing Controllers
*/
public abstract class ControllerPagerAdapter extends PagerAdapter {
private final Controller mHost;
private static final String KEY_SAVED_PAGES = "ControllerPagerAdapter.savedStates";
private static final String KEY_SAVES_STATE = "ControllerPagerAdapter.savesState";
private final Controller host;
private boolean savesState;
private SparseArray<Bundle> savedPages = new SparseArray<>();
/**
* Creates a new ControllerPagerAdapter using the passed host.
*/
public ControllerPagerAdapter(Controller host) {
mHost = host;
public ControllerPagerAdapter(Controller host, boolean saveControllerState) {
this.host = host;
savesState = saveControllerState;
}
/**
@@ -30,21 +40,36 @@ public abstract class ControllerPagerAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup container, int position) {
final String name = makeControllerName(container.getId(), getItemId(position));
Controller controller = mHost.getChildController(name);
if (controller == null) {
controller = getItem(position);
Router router = host.getChildRouter(container, name);
if (savesState && !router.hasRootController()) {
Bundle routerSavedState = savedPages.get(position);
mHost.addChildController(ChildControllerTransaction.builder(controller, container.getId())
.tag(name)
.build());
if (routerSavedState != null) {
router.restoreInstanceState(routerSavedState);
}
}
return controller;
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(getItem(position))
.tag(name));
} else {
router.rebindIfNeeded();
}
return router.getControllerWithTag(name);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
mHost.removeChildController((Controller)object);
Router router = ((Controller)object).getRouter();
if (savesState) {
Bundle savedState = new Bundle();
router.saveInstanceState(savedState);
savedPages.put(position, savedState);
}
host.removeChildRouter(router);
}
@Override
@@ -52,6 +77,23 @@ public abstract class ControllerPagerAdapter extends PagerAdapter {
return ((Controller)object).getView() == view;
}
@Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
bundle.putBoolean(KEY_SAVES_STATE, savesState);
bundle.putSparseParcelableArray(KEY_SAVED_PAGES, savedPages);
return bundle;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = (Bundle)state;
if (state != null) {
savesState = bundle.getBoolean(KEY_SAVES_STATE, false);
savedPages = bundle.getSparseParcelableArray(KEY_SAVED_PAGES);
}
}
public long getItemId(int position) {
return position;
}
+22 -3
View File
@@ -26,16 +26,23 @@ android {
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName
versionCode Integer.parseInt(project.VERSION_CODE)
versionName project.VERSION_NAME
consumerProguardFiles 'proguard-rules.txt'
}
}
configurations {
lintChecks
}
dependencies {
testCompile rootProject.ext.junit
testCompile rootProject.ext.roboelectric
compile rootProject.ext.supportAnnotations
lintChecks project(path: ':conductor-lint', configuration: 'lintChecks')
}
unMock {
@@ -46,7 +53,19 @@ unMock {
keep "android.text.TextUtils"
}
task copyLintJar(type: Copy) {
from(configurations.lintChecks) {
rename { 'lint.jar' }
}
into 'build/intermediates/lint/'
}
project.afterEvaluate {
def compileLintTask = project.tasks.find { it.name == 'compileLint' }
compileLintTask.dependsOn(copyLintJar)
}
ext.artifactId = 'conductor'
apply from: rootProject.file('dependencies.gradle')
apply from: rootProject.file('bll-gradle-push.gradle')
apply from: rootProject.file('gradle-mvn-push.gradle')
+3
View File
@@ -0,0 +1,3 @@
POM_NAME=Conductor
POM_ARTIFACT_ID=conductor
POM_PACKAGING=aar
+5
View File
@@ -0,0 +1,5 @@
# Retain constructor that is called by using reflection to recreate the Controller
-keepclassmembers public class * extends com.bluelinelabs.conductor.Controller {
public <init>();
public <init>(android.os.Bundle);
}
@@ -0,0 +1,100 @@
package com.bluelinelabs.conductor;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.ControllerChangeHandler.ControllerChangeListener;
import com.bluelinelabs.conductor.internal.LifecycleHandler;
import java.util.List;
public class ActivityHostedRouter extends Router {
private LifecycleHandler lifecycleHandler;
public final void setHost(@NonNull LifecycleHandler lifecycleHandler, @NonNull ViewGroup container) {
if (this.lifecycleHandler != lifecycleHandler || this.container != container) {
if (this.container != null && this.container instanceof ControllerChangeListener) {
removeChangeListener((ControllerChangeListener)this.container);
}
if (container instanceof ControllerChangeListener) {
addChangeListener((ControllerChangeListener)container);
}
this.lifecycleHandler = lifecycleHandler;
this.container = container;
}
}
@Override
public Activity getActivity() {
return lifecycleHandler != null ? lifecycleHandler.getLifecycleActivity() : null;
}
@Override
public void onActivityDestroyed(Activity activity) {
super.onActivityDestroyed(activity);
lifecycleHandler = null;
}
@Override
public final void invalidateOptionsMenu() {
if (lifecycleHandler != null && lifecycleHandler.getFragmentManager() != null) {
lifecycleHandler.getFragmentManager().invalidateOptionsMenu();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
lifecycleHandler.onActivityResult(requestCode, resultCode, data);
}
@Override
void startActivity(Intent intent) {
lifecycleHandler.startActivity(intent);
}
@Override
void startActivityForResult(String instanceId, Intent intent, int requestCode) {
lifecycleHandler.startActivityForResult(instanceId, intent, requestCode);
}
@Override
void startActivityForResult(String instanceId, Intent intent, int requestCode, Bundle options) {
lifecycleHandler.startActivityForResult(instanceId, intent, requestCode, options);
}
@Override
void registerForActivityResult(String instanceId, int requestCode) {
lifecycleHandler.registerForActivityResult(instanceId, requestCode);
}
@Override
void unregisterForActivityResults(String instanceId) {
lifecycleHandler.unregisterForActivityResults(instanceId);
}
@Override
void requestPermissions(String instanceId, @NonNull String[] permissions, int requestCode) {
lifecycleHandler.requestPermissions(instanceId, permissions, requestCode);
}
@Override
boolean hasHost() {
return lifecycleHandler != null;
}
@Override
List<Router> getSiblingRouters() {
return lifecycleHandler.getRouters();
}
@Override
Router getRootRouter() {
return this;
}
}
@@ -5,6 +5,7 @@ import android.os.Bundle;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
@@ -12,34 +13,34 @@ class Backstack implements Iterable<RouterTransaction> {
private static final String KEY_ENTRIES = "Backstack.entries";
private final ArrayDeque<RouterTransaction> mBackStack = new ArrayDeque<>();
private final Deque<RouterTransaction> backStack = new ArrayDeque<>();
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isEmpty() {
return mBackStack.isEmpty();
return backStack.isEmpty();
}
public int size() {
return mBackStack.size();
return backStack.size();
}
public RouterTransaction root() {
return mBackStack.size() > 0 ? mBackStack.getLast() : null;
return backStack.size() > 0 ? backStack.getLast() : null;
}
@Override
public Iterator<RouterTransaction> iterator() {
return mBackStack.iterator();
return backStack.iterator();
}
public Iterator<RouterTransaction> reverseIterator() {
return mBackStack.descendingIterator();
return backStack.descendingIterator();
}
public List<RouterTransaction> popTo(RouterTransaction transaction) {
List<RouterTransaction> popped = new ArrayList<>();
if (mBackStack.contains(transaction)) {
while (mBackStack.peek() != transaction) {
if (backStack.contains(transaction)) {
while (backStack.peek() != transaction) {
RouterTransaction poppedTransaction = pop();
popped.add(poppedTransaction);
}
@@ -50,33 +51,56 @@ class Backstack implements Iterable<RouterTransaction> {
}
public RouterTransaction pop() {
RouterTransaction popped = mBackStack.pop();
popped.getController().destroy();
RouterTransaction popped = backStack.pop();
popped.controller.destroy();
return popped;
}
public RouterTransaction peek() {
return mBackStack.peek();
return backStack.peek();
}
public void remove(RouterTransaction transaction) {
mBackStack.removeFirstOccurrence(transaction);
backStack.removeFirstOccurrence(transaction);
}
public void push(RouterTransaction transaction) {
mBackStack.push(transaction);
backStack.push(transaction);
}
public void popAll() {
public List<RouterTransaction> popAll() {
List<RouterTransaction> list = new ArrayList<>();
while (!isEmpty()) {
pop();
list.add(pop());
}
return list;
}
public void setBackstack(List<RouterTransaction> backstack) {
for (RouterTransaction existingTransaction : backStack) {
boolean contains = false;
for (RouterTransaction newTransaction : backstack) {
if (existingTransaction.controller == newTransaction.controller) {
contains = true;
break;
}
}
if (!contains) {
existingTransaction.controller.destroy();
}
}
backStack.clear();
for (RouterTransaction transaction : backstack) {
backStack.push(transaction);
}
}
public void saveInstanceState(Bundle outState) {
ArrayList<Bundle> entryBundles = new ArrayList<>(mBackStack.size());
for (RouterTransaction entry : mBackStack) {
entryBundles.add(entry.toBundle());
ArrayList<Bundle> entryBundles = new ArrayList<>(backStack.size());
for (RouterTransaction entry : backStack) {
entryBundles.add(entry.saveInstanceState());
}
outState.putParcelableArrayList(KEY_ENTRIES, entryBundles);
@@ -87,7 +111,7 @@ class Backstack implements Iterable<RouterTransaction> {
if (entryBundles != null) {
Collections.reverse(entryBundles);
for (Bundle transactionBundle : entryBundles) {
mBackStack.push(new RouterTransaction(transactionBundle));
backStack.push(new RouterTransaction(transactionBundle));
}
}
}
@@ -17,7 +17,7 @@ import com.bluelinelabs.conductor.ControllerChangeHandler.ControllerChangeListen
*/
public class ChangeHandlerFrameLayout extends FrameLayout implements ControllerChangeListener {
private int mInProgressTransactionCount;
private int inProgressTransactionCount;
public ChangeHandlerFrameLayout(Context context) {
super(context);
@@ -38,16 +38,17 @@ public class ChangeHandlerFrameLayout extends FrameLayout implements ControllerC
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return (mInProgressTransactionCount > 0) || super.onInterceptTouchEvent(ev);
return (inProgressTransactionCount > 0) || super.onInterceptTouchEvent(ev);
}
@Override
public void onChangeStarted(Controller to, Controller from, boolean isPush, ViewGroup container, ControllerChangeHandler handler) {
mInProgressTransactionCount++;
inProgressTransactionCount++;
}
@Override
public void onChangeCompleted(Controller to, Controller from, boolean isPush, ViewGroup container, ControllerChangeHandler handler) {
mInProgressTransactionCount--;
inProgressTransactionCount--;
}
}
@@ -1,79 +0,0 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
/**
* A {@link ControllerTransaction} implementation used for adding child {@link Controller}s.
*/
public class ChildControllerTransaction extends ControllerTransaction {
private static final String KEY_CONTAINER_ID = "ChildControllerTransaction.containerId";
private static final String KEY_ADD_TO_LOCAL_BACKSTACK = "ChildControllerTransaction.addToLocalBackstack";
/** The ID of the ViewGroup that the child {@link Controller} will be added to */
public final int containerId;
/** If true, the hosting {@link Controller} will be responsible for reversing this transaction if the user presses the back button */
public final boolean addToLocalBackstack;
ChildControllerTransaction(Builder builder) {
super(builder);
containerId = builder.containerId;
addToLocalBackstack = builder.addToLocalBackstack;
}
ChildControllerTransaction(@NonNull Bundle bundle) {
super(bundle);
containerId = bundle.getInt(KEY_CONTAINER_ID);
addToLocalBackstack = bundle.getBoolean(KEY_ADD_TO_LOCAL_BACKSTACK);
}
@Override
public Bundle toBundle() {
Bundle bundle = super.toBundle();
bundle.putInt(KEY_CONTAINER_ID, containerId);
bundle.putBoolean(KEY_ADD_TO_LOCAL_BACKSTACK, addToLocalBackstack);
return bundle;
}
/**
* Creates a new Builder
*
* @param controller The Controller to add as a child
* @param containerId The ID of the ViewGroup to which the controller's view should be added
*/
public static Builder builder(@NonNull Controller controller, @IdRes int containerId) {
return new Builder(controller, containerId);
}
/**
* A {@link ControllerTransaction.Builder} implementation used for adding child {@link Controller}s.
*/
public static class Builder extends ControllerTransaction.Builder<Builder> {
@IdRes final int containerId;
boolean addToLocalBackstack;
Builder(@NonNull Controller controller, @IdRes int containerId) {
super(controller);
this.containerId = containerId;
}
/**
* If true, the hosting {@link Controller} will be responsible for reversing this transaction if the user presses the back button.
*/
public Builder addToLocalBackstack(boolean addToLocalBackstack) {
this.addToLocalBackstack = addToLocalBackstack;
return this;
}
/** Creates the transaction */
public ChildControllerTransaction build() {
return new ChildControllerTransaction(this);
}
}
}
@@ -10,8 +10,10 @@ import com.bluelinelabs.conductor.internal.LifecycleHandler;
/**
* Point of initial interaction with Conductor. Used to attach a {@link Router} to your Activity.
*/
public class Conductor {
public final class Conductor {
private Conductor() {}
/**
* Conductor will create a {@link Router} that has been initialized for your Activity and containing ViewGroup.
* If an existing {@link Router} is already associated with this Activity/ViewGroup pair, either in memory
File diff suppressed because it is too large Load Diff
+83 -17
View File
@@ -2,16 +2,17 @@ package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.bluelinelabs.conductor.ControllerTransaction.ControllerChangeType;
import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler;
import com.bluelinelabs.conductor.internal.ClassUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ControllerChangeHandlers are responsible for swapping the View for one Controller to the View
@@ -23,13 +24,17 @@ public abstract class ControllerChangeHandler {
private static final String KEY_CLASS_NAME = "ControllerChangeHandler.className";
private static final String KEY_SAVED_STATE = "ControllerChangeHandler.savedState";
private static final Map<String, ControllerChangeHandler> inProgressPushHandlers = new HashMap<>();
private boolean forceRemoveViewOnPush;
/**
* Responsible for swapping Views from one Controller to another.
*
* @param container The container these Views are hosted in.
* @param from The previous View in the container, if any.
* @param to The next View that should be put in the container, if any.
* @param isPush True if this is a push transaction, false if it's a pop.
* @param container The container these Views are hosted in.
* @param from The previous View in the container, if any.
* @param to The next View that should be put in the container, if any.
* @param isPush True if this is a push transaction, false if it's a pop.
* @param changeListener This listener must be called when any transitions or animations are completed.
*/
public abstract void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener);
@@ -52,9 +57,24 @@ public abstract class ControllerChangeHandler {
*/
public void restoreFromBundle(@NonNull Bundle bundle) { }
/**
* Will be called on change handlers that push a controller if the controller being pushed is
* popped before it has completed.
*
* @param newHandler the change handler that has caused this push to be aborted
* @param newTop the controller that will now be at the top of the backstack
*/
public void onAbortPush(@NonNull ControllerChangeHandler newHandler, Controller newTop) { }
/**
* Will be called on change handlers that push a controller if the controller being pushed is
* needs to be attached immediately, without any animations or transitions.
*/
public void completeImmediately() { }
final Bundle toBundle() {
Bundle bundle = new Bundle();
bundle.putString(KEY_CLASS_NAME, getClass().getCanonicalName());
bundle.putString(KEY_CLASS_NAME, getClass().getName());
Bundle savedState = new Bundle();
saveToBundle(savedState);
@@ -63,6 +83,10 @@ public abstract class ControllerChangeHandler {
return bundle;
}
final ControllerChangeHandler copy() {
return fromBundle(toBundle());
}
private void ensureDefaultConstructor() {
try {
getClass().getConstructor();
@@ -71,7 +95,7 @@ public abstract class ControllerChangeHandler {
}
}
public static ControllerChangeHandler fromBundle(@Nullable Bundle bundle) {
public static ControllerChangeHandler fromBundle(Bundle bundle) {
if (bundle != null) {
String className = bundle.getString(KEY_CLASS_NAME);
ControllerChangeHandler changeHandler = ClassUtils.newInstance(className);
@@ -83,12 +107,38 @@ public abstract class ControllerChangeHandler {
}
}
static boolean completePushImmediately(String controllerInstanceId) {
ControllerChangeHandler changeHandler = inProgressPushHandlers.get(controllerInstanceId);
if (changeHandler != null) {
changeHandler.completeImmediately();
inProgressPushHandlers.remove(controllerInstanceId);
return true;
}
return false;
}
public static void abortPush(Controller toAbort, Controller newController, ControllerChangeHandler newChangeHandler) {
ControllerChangeHandler handlerForPush = inProgressPushHandlers.get(toAbort.getInstanceId());
if (handlerForPush != null) {
handlerForPush.onAbortPush(newChangeHandler, newController);
inProgressPushHandlers.remove(toAbort.getInstanceId());
}
}
public static void executeChange(final Controller to, final Controller from, boolean isPush, ViewGroup container, ControllerChangeHandler inHandler) {
executeChange(to, from, isPush, container, inHandler, new ArrayList<ControllerChangeListener>());
}
public static void executeChange(final Controller to, final Controller from, final boolean isPush, final ViewGroup container, final ControllerChangeHandler inHandler, @NonNull final List<ControllerChangeListener> listeners) {
if (container != null) {
final ControllerChangeHandler handler = inHandler != null ? inHandler : new SimpleSwapChangeHandler();
if (isPush && to != null) {
inProgressPushHandlers.put(to.getInstanceId(), handler);
} else if (!isPush && from != null) {
abortPush(from, to, handler);
}
for (ControllerChangeListener listener : listeners) {
listener.onChangeStarted(to, from, isPush, container, inHandler);
}
@@ -96,7 +146,6 @@ public abstract class ControllerChangeHandler {
final ControllerChangeType toChangeType = isPush ? ControllerChangeType.PUSH_ENTER : ControllerChangeType.POP_ENTER;
final ControllerChangeType fromChangeType = isPush ? ControllerChangeType.PUSH_EXIT : ControllerChangeType.POP_EXIT;
final ControllerChangeHandler handler = inHandler != null ? inHandler : new SimpleSwapChangeHandler();
final View toView;
if (to != null) {
toView = to.inflate(container);
@@ -121,17 +170,33 @@ public abstract class ControllerChangeHandler {
}
if (to != null) {
inProgressPushHandlers.remove(to.getInstanceId());
to.changeEnded(handler, toChangeType);
}
for (ControllerChangeListener listener : listeners) {
listener.onChangeCompleted(to, from, isPush, container, inHandler);
}
if (handler.forceRemoveViewOnPush && fromView != null) {
ViewParent fromParent = fromView.getParent();
if (fromParent != null && fromParent instanceof ViewGroup) {
((ViewGroup)fromParent).removeView(fromView);
}
}
}
});
}
}
public boolean removesFromViewOnPush() {
return true;
}
public void setForceRemoveViewOnPush(boolean force) {
forceRemoveViewOnPush = force;
}
/**
* A listener interface useful for allowing external classes to be notified of change events.
*/
@@ -139,21 +204,22 @@ public abstract class ControllerChangeHandler {
/**
* Called when a {@link ControllerChangeHandler} has started changing {@link Controller}s
*
* @param to The new Controller
* @param from The old Controller
* @param isPush True if this is a push operation, or false if it's a pop.
* @param to The new Controller
* @param from The old Controller
* @param isPush True if this is a push operation, or false if it's a pop.
* @param container The containing ViewGroup
* @param handler The change handler being used.
* @param handler The change handler being used.
*/
void onChangeStarted(Controller to, Controller from, boolean isPush, ViewGroup container, ControllerChangeHandler handler);
/**
* Called when a {@link ControllerChangeHandler} has completed changing {@link Controller}s
* @param to The new Controller
* @param from The old Controller
* @param isPush True if this was a push operation, or false if it's a pop.
*
* @param to The new Controller
* @param from The old Controller
* @param isPush True if this was a push operation, or false if it's a pop.
* @param container The containing ViewGroup
* @param handler The change handler that was used.
* @param handler The change handler that was used.
*/
void onChangeCompleted(Controller to, Controller from, boolean isPush, ViewGroup container, ControllerChangeHandler handler);
}
@@ -0,0 +1,26 @@
package com.bluelinelabs.conductor;
/**
* All possible types of {@link Controller} changes to be used in {@link ControllerChangeHandler}s
*/
public enum ControllerChangeType {
/** The Controller is being pushed to the host container */
PUSH_ENTER(true, true),
/** The Controller is being pushed to the backstack as another Controller is pushed to the host container */
PUSH_EXIT(true, false),
/** The Controller is being popped from the backstack and placed in the host container as another Controller is popped */
POP_ENTER(false, true),
/** The Controller is being popped from the host container */
POP_EXIT(false, false);
public boolean isPush;
public boolean isEnter;
ControllerChangeType(boolean isPush, boolean isEnter) {
this.isPush = isPush;
this.isEnter = isEnter;
}
}
@@ -0,0 +1,198 @@
package com.bluelinelabs.conductor;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.ControllerChangeHandler.ControllerChangeListener;
import java.util.ArrayList;
import java.util.List;
class ControllerHostedRouter extends Router {
private final String KEY_HOST_ID = "ControllerHostedRouter.hostId";
private final String KEY_TAG = "ControllerHostedRouter.tag";
private Controller hostController;
@IdRes private int hostId;
private String tag;
ControllerHostedRouter() { }
ControllerHostedRouter(int hostId, String tag) {
this.hostId = hostId;
this.tag = tag;
}
final void setHost(@NonNull Controller controller, @NonNull ViewGroup container) {
if (hostController != controller || this.container != container) {
removeHost();
if (container instanceof ControllerChangeListener) {
addChangeListener((ControllerChangeListener)container);
}
hostController = controller;
this.container = container;
}
}
final void removeHost() {
if (container != null && container instanceof ControllerChangeListener) {
removeChangeListener((ControllerChangeListener)container);
}
final List<Controller> controllersToDestroy = new ArrayList<>(destroyingControllers);
for (Controller controller : controllersToDestroy) {
if (controller.getView() != null) {
controller.detach(controller.getView(), true);
}
}
for (RouterTransaction transaction : backstack) {
if (transaction.controller.getView() != null) {
transaction.controller.detach(transaction.controller.getView(), true);
}
}
prepareForContainerRemoval();
hostController = null;
container = null;
}
final void setDetachFrozen(boolean frozen) {
for (RouterTransaction transaction : backstack) {
transaction.controller.setDetachFrozen(frozen);
}
}
@Override
void destroy() {
setDetachFrozen(false);
super.destroy();
}
@Override
public Activity getActivity() {
return hostController != null ? hostController.getActivity() : null;
}
@Override
public void onActivityDestroyed(Activity activity) {
super.onActivityDestroyed(activity);
removeHost();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void invalidateOptionsMenu() {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().invalidateOptionsMenu();
}
}
@Override
void startActivity(Intent intent) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().startActivity(intent);
}
}
@Override
void startActivityForResult(String instanceId, Intent intent, int requestCode) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().startActivityForResult(instanceId, intent, requestCode);
}
}
@Override
void startActivityForResult(String instanceId, Intent intent, int requestCode, Bundle options) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().startActivityForResult(instanceId, intent, requestCode, options);
}
}
@Override
void registerForActivityResult(String instanceId, int requestCode) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().registerForActivityResult(instanceId, requestCode);
}
}
@Override
void unregisterForActivityResults(String instanceId) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().unregisterForActivityResults(instanceId);
}
}
@Override
void requestPermissions(String instanceId, String[] permissions, int requestCode) {
if (hostController != null && hostController.getRouter() != null) {
hostController.getRouter().requestPermissions(instanceId, permissions, requestCode);
}
}
@Override
boolean hasHost() {
return hostController != null;
}
@Override
public void saveInstanceState(Bundle outState) {
super.saveInstanceState(outState);
outState.putInt(KEY_HOST_ID, hostId);
outState.putString(KEY_TAG, tag);
}
@Override
public void restoreInstanceState(Bundle savedInstanceState) {
super.restoreInstanceState(savedInstanceState);
hostId = savedInstanceState.getInt(KEY_HOST_ID);
tag = savedInstanceState.getString(KEY_TAG);
}
@Override
void setControllerRouter(Controller controller) {
super.setControllerRouter(controller);
controller.setParentController(hostController);
}
int getHostId() {
return hostId;
}
String getTag() {
return tag;
}
@Override
List<Router> getSiblingRouters() {
List<Router> list = new ArrayList<>();
list.addAll(hostController.getChildRouters());
list.addAll(hostController.getRouter().getSiblingRouters());
return list;
}
@Override
Router getRootRouter() {
if (hostController != null && hostController.getRouter() != null) {
return hostController.getRouter().getRootRouter();
} else {
return this;
}
}
}
@@ -1,148 +0,0 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.NonNull;
/**
* Metadata used to transition between {@link Controller}s.
*/
public class ControllerTransaction {
/**
* All possible types of {@link Controller} changes to be used in {@link ControllerChangeHandler}s
*/
public enum ControllerChangeType {
/** The Controller is being pushed to the host container */
PUSH_ENTER,
/** The Controller is being pushed to the backstack as another Controller is pushed to the host container */
PUSH_EXIT,
/** The Controller is being popped from the backstack and placed in the host container as another Controller is popped */
POP_ENTER,
/** The Controller is being popped from the host contianer */
POP_EXIT
}
private static final String KEY_VIEW_CONTROLLER_BUNDLE = "ControllerTransaction.controller.bundle";
private static final String KEY_PUSH_TRANSITION = "ControllerTransaction.pushControllerChangeHandler";
private static final String KEY_POP_TRANSITION = "ControllerTransaction.popControllerChangeHandler";
private static final String KEY_TAG = "ControllerTransaction.tag";
public final Controller controller;
public final String tag;
private final ControllerChangeHandler mPushControllerChangeHandler;
private final ControllerChangeHandler mPopControllerChangeHandler;
ControllerTransaction(Builder builder) {
controller = builder.controller;
tag = builder.tag;
mPushControllerChangeHandler = builder.pushControllerChangeHandler;
mPopControllerChangeHandler = builder.popControllerChangeHandler;
}
ControllerTransaction(@NonNull Bundle bundle) {
controller = Controller.newInstance(bundle.getBundle(KEY_VIEW_CONTROLLER_BUNDLE));
mPushControllerChangeHandler = ControllerChangeHandler.fromBundle(bundle.getBundle(KEY_PUSH_TRANSITION));
mPopControllerChangeHandler = ControllerChangeHandler.fromBundle(bundle.getBundle(KEY_POP_TRANSITION));
tag = bundle.getString(KEY_TAG);
}
public Controller getController() {
return controller;
}
public String getTag() {
return tag;
}
public ControllerChangeHandler getPushControllerChangeHandler() {
ControllerChangeHandler handler = controller.getOverriddenPushHandler();
if (handler == null) {
handler = mPushControllerChangeHandler;
}
return handler;
}
public ControllerChangeHandler getPopControllerChangeHandler() {
ControllerChangeHandler handler = controller.getOverriddenPopHandler();
if (handler == null) {
handler = mPopControllerChangeHandler;
}
return handler;
}
/**
* Used to serialize this transaction into a Bundle
*/
public Bundle toBundle() {
Bundle bundle = new Bundle();
bundle.putBundle(KEY_VIEW_CONTROLLER_BUNDLE, controller.saveInstanceState());
if (mPushControllerChangeHandler != null) {
bundle.putBundle(KEY_PUSH_TRANSITION, mPushControllerChangeHandler.toBundle());
}
if (mPopControllerChangeHandler != null) {
bundle.putBundle(KEY_POP_TRANSITION, mPopControllerChangeHandler.toBundle());
}
bundle.putString(KEY_TAG, tag);
return bundle;
}
/**
* Builder used to create transactions.
*/
public static class Builder<T extends Builder<T>> {
final Controller controller;
ControllerChangeHandler pushControllerChangeHandler;
ControllerChangeHandler popControllerChangeHandler;
String tag;
public Builder(@NonNull Controller controller) {
this.controller = controller;
}
/**
* The {@link ControllerChangeHandler} that will be used when the {@link Controller} is pushed
* to the screen.
*/
@SuppressWarnings("unchecked")
public T pushChangeHandler(ControllerChangeHandler pushControllerChangeHandler) {
this.pushControllerChangeHandler = pushControllerChangeHandler;
return (T)this;
}
/**
* The {@link ControllerChangeHandler} that will be used when the {@link Controller} is popped
* from the screen.
*/
@SuppressWarnings("unchecked")
public T popChangeHandler(ControllerChangeHandler popControllerChangeHandler) {
this.popControllerChangeHandler = popControllerChangeHandler;
return (T)this;
}
/**
* The tag to use for this transaction. Tags can be used for finding transactions later on.
*/
@SuppressWarnings("unchecked")
public T tag(String tag) {
this.tag = tag;
return (T)this;
}
/**
* Creates the transaction.
*/
public ControllerTransaction build() {
return new ControllerTransaction(this);
}
}
}
@@ -0,0 +1,38 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple controller subclass that changes the onCreateView signature to include a saved view state parameter.
* This is necessary for some third party libraries like Google Maps, which require passing in a saved state
* bundle at the time of creation.
*/
abstract public class RestoreViewOnCreateController extends Controller {
@NonNull
@Override
protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return onCreateView(inflater, container, viewState);
}
/**
* Called when the controller is ready to display its view. A valid view must be returned. The standard body
* for this method will be {@code return inflater.inflate(R.layout.my_layout, container, false);}, plus
* any binding and state restoration code.
*
* @param inflater The LayoutInflater that should be used to inflate views
* @param container The parent view that this Controller's view will eventually be attached to.
* This Controller's view should NOT be added in this method. It is simply passed in
* so that valid LayoutParams can be used during inflation.
* @param savedViewState A bundle for the view's state, which would have been created in {@link #onSaveViewState(View, Bundle)},
* or null if no saved state exists.
*/
@NonNull
protected abstract View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container, @Nullable Bundle savedViewState);
}
@@ -4,14 +4,19 @@ import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Controller.LifecycleListener;
import com.bluelinelabs.conductor.ControllerChangeHandler.ControllerChangeListener;
import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler;
import com.bluelinelabs.conductor.internal.LifecycleHandler;
import com.bluelinelabs.conductor.internal.NoOpControllerChangeHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
@@ -20,35 +25,33 @@ import java.util.List;
* to Activity/containing ViewGroup pairs. Routers do not directly render or push Views to the container ViewGroup,
* but instead defer this responsibility to the {@link ControllerChangeHandler} specified in a given transaction.
*/
public class Router {
public abstract class Router {
private final Backstack mBackStack = new Backstack();
private LifecycleHandler mLifecycleHandler;
private ViewGroup mContainer;
private final List<ControllerChangeListener> mChangeListeners = new ArrayList<>();
private static final String KEY_BACKSTACK = "Router.backstack";
private static final String KEY_POPS_LAST_VIEW = "Router.popsLastView";
protected final Backstack backstack = new Backstack();
private final List<ControllerChangeListener> changeListeners = new ArrayList<>();
final List<Controller> destroyingControllers = new ArrayList<>();
private boolean popsLastView = false;
ViewGroup container;
/**
* Returns this Router's host Activity
*/
public Activity getActivity() {
return mLifecycleHandler.getLifecycleActivity();
}
public abstract Activity getActivity();
/**
* This should be called by the host Activity when its onActivityResult method is called. The call will be forwarded
* to the {@link Controller} with the instanceId passed in.
* This should be called by the host Activity when its onActivityResult method is called if the instanceId
* of the controller that called startActivityForResult is not known.
*
* @param instanceId The instanceId of the Controller to which this result should be forwarded
* @param requestCode The Activity's onActivityResult requestCode
* @param resultCode The Activity's onActivityResult resultCode
* @param data The Activity's onActivityResult data
*/
public void onActivityResult(String instanceId, int requestCode, int resultCode, Intent data) {
Controller controller = getControllerWithInstanceId(instanceId);
if (controller != null) {
controller.onActivityResult(requestCode, resultCode, data);
}
}
public abstract void onActivityResult(int requestCode, int resultCode, Intent data);
/**
* This should be called by the host Activity when its onRequestPermissionsResult method is called. The call will be forwarded
@@ -69,10 +72,12 @@ public class Router {
/**
* This should be called by the host Activity when its onBackPressed method is called. The call will be forwarded
* to its top {@link Controller}. If that controller doesn't handle it, then it will be popped.
*
* @return Whether or not a back action was handled by the Router
*/
public boolean handleBack() {
if (!mBackStack.isEmpty()) {
if (mBackStack.peek().controller.handleBack()) {
if (!backstack.isEmpty()) {
if (backstack.peek().controller.handleBack()) {
return true;
} else if (popCurrentController()) {
return true;
@@ -88,7 +93,7 @@ public class Router {
* @return Whether or not this Router still has controllers remaining on it after popping.
*/
public boolean popCurrentController() {
return popController(mBackStack.peek().controller);
return popController(backstack.peek().controller);
}
/**
@@ -98,25 +103,29 @@ public class Router {
* @return Whether or not this Router still has controllers remaining on it after popping.
*/
public boolean popController(Controller controller) {
RouterTransaction topController = mBackStack.peek();
boolean poppingTopController = topController.controller == controller;
RouterTransaction topController = backstack.peek();
boolean poppingTopController = topController != null && topController.controller == controller;
if (poppingTopController) {
mBackStack.pop();
trackDestroyingController(backstack.pop());
} else {
for (RouterTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
if (transaction.controller == controller) {
mBackStack.remove(transaction);
backstack.remove(transaction);
break;
}
}
}
if (poppingTopController) {
performControllerChange(mBackStack.peek(), topController, false);
performControllerChange(backstack.peek(), topController, false);
}
return !mBackStack.isEmpty();
if (popsLastView) {
return topController != null;
} else {
return !backstack.isEmpty();
}
}
/**
@@ -126,7 +135,7 @@ public class Router {
* and its push and pop {@link ControllerChangeHandler}, and its tag.
*/
public void pushController(@NonNull RouterTransaction transaction) {
RouterTransaction from = mBackStack.peek();
RouterTransaction from = backstack.peek();
pushToBackstack(transaction);
performControllerChange(transaction, from, true);
}
@@ -138,13 +147,51 @@ public class Router {
* and its push and pop {@link ControllerChangeHandler}, and its tag.
*/
public void replaceTopController(@NonNull RouterTransaction transaction) {
RouterTransaction topTransaction = mBackStack.peek();
if (!mBackStack.isEmpty()) {
mBackStack.pop();
RouterTransaction topTransaction = backstack.peek();
if (!backstack.isEmpty()) {
trackDestroyingController(backstack.pop());
}
final ControllerChangeHandler handler = transaction.pushChangeHandler();
final boolean oldHandlerRemovedViews = topTransaction.pushChangeHandler() == null || topTransaction.pushChangeHandler().removesFromViewOnPush();
final boolean newHandlerRemovesViews = handler == null || handler.removesFromViewOnPush();
if (!oldHandlerRemovedViews && newHandlerRemovesViews) {
for (RouterTransaction visibleTransaction : getVisibleTransactions(backstack.iterator())) {
performControllerChange(null, visibleTransaction.controller, true, handler != null ? handler.copy() : new SimpleSwapChangeHandler());
}
}
pushToBackstack(transaction);
performControllerChange(transaction, topTransaction, true);
if (handler != null) {
handler.setForceRemoveViewOnPush(true);
}
performControllerChange(transaction.pushChangeHandler(handler), topTransaction, true);
}
void destroy() {
popsLastView = true;
List<RouterTransaction> poppedControllers = backstack.popAll();
if (poppedControllers.size() > 0) {
trackDestroyingControllers(poppedControllers);
performControllerChange(null, poppedControllers.get(0).controller, false, poppedControllers.get(0).popChangeHandler());
}
}
public int getContainerId() {
return container != null ? container.getId() : 0;
}
/**
* If set to true, this router will handle back presses by performing a change handler on the last controller and view
* in the stack. This defaults to false so that the developer can either finish its containing Activity or otherwise
* hide its parent view without any strange artifacting.
*/
public Router setPopsLastView(boolean popsLastView) {
this.popsLastView = popsLastView;
return this;
}
/**
@@ -163,8 +210,8 @@ public class Router {
* @return Whether or not any {@link Controller}s were popped in order to get to the root transaction
*/
public boolean popToRoot(ControllerChangeHandler changeHandler) {
if (mBackStack.size() > 1) {
popToTransaction(mBackStack.root(), changeHandler);
if (backstack.size() > 1) {
popToTransaction(backstack.root(), changeHandler);
return true;
} else {
return false;
@@ -189,8 +236,8 @@ public class Router {
* @return Whether or not the {@link Controller} with the passed tag is now at the top
*/
public boolean popToTag(@NonNull String tag, ControllerChangeHandler changeHandler) {
for (RouterTransaction transaction : mBackStack) {
if (tag.equals(transaction.tag)) {
for (RouterTransaction transaction : backstack) {
if (tag.equals(transaction.tag())) {
popToTransaction(transaction, changeHandler);
return true;
}
@@ -198,33 +245,36 @@ public class Router {
return false;
}
/**
* Sets the root {@link Controller}. If any {@link Controller} are currently in the backstack, they will be removed.
*
* @param controller The new root {@link Controller}
*/
public void setRoot(@NonNull Controller controller) {
setRoot(controller, null);
}
/**
* Sets the root Controller. If any {@link Controller}s are currently in the backstack, they will be removed.
*
* @param controller The new root {@link Controller}
* @param tag The tag to use for this {@link Controller}
* @param transaction The transaction detailing what should be pushed, including the {@link Controller},
* and its push and pop {@link ControllerChangeHandler}, and its tag.
*/
public void setRoot(@NonNull Controller controller, String tag) {
mContainer.removeAllViews();
mBackStack.popAll();
public void setRoot(@NonNull RouterTransaction transaction) {
ControllerChangeHandler newHandler = transaction.pushChangeHandler() != null ? transaction.pushChangeHandler() : new SimpleSwapChangeHandler();
RouterTransaction transaction = RouterTransaction.builder(controller)
.tag(tag)
.pushChangeHandler(new SimpleSwapChangeHandler())
.popChangeHandler(new SimpleSwapChangeHandler())
.build();
List<RouterTransaction> visibleTransactions = getVisibleTransactions(backstack.iterator());
RouterTransaction rootTransaction = visibleTransactions.size() > 0 ? visibleTransactions.get(0) : null;
removeAllExceptVisibleAndUnowned();
trackDestroyingControllers(backstack.popAll());
pushToBackstack(transaction);
performControllerChange(transaction, null, true);
for (int i = visibleTransactions.size() - 1; i > 0; i--) {
if (visibleTransactions.get(i).controller.getView() == null) {
ControllerChangeHandler.abortPush(visibleTransactions.get(i).controller, transaction.controller, newHandler);
} else {
performControllerChange(null, visibleTransactions.get(i).controller, true, newHandler);
}
}
if (rootTransaction != null && rootTransaction.controller.getView() == null) {
ControllerChangeHandler.abortPush(rootTransaction.controller, transaction.controller, newHandler);
}
performControllerChange(transaction, rootTransaction, true);
}
/**
@@ -234,14 +284,10 @@ public class Router {
* @return The matching Controller, if one exists
*/
public Controller getControllerWithInstanceId(String instanceId) {
for (ControllerTransaction transaction : mBackStack) {
if (transaction.controller.getInstanceId().equals(instanceId)) {
return transaction.controller;
} else {
Controller childWithId = transaction.controller.getChildControllerWithInstanceId(instanceId);
if (childWithId != null) {
return childWithId;
}
for (RouterTransaction transaction : backstack) {
Controller controllerWithId = transaction.controller.findController(instanceId);
if (controllerWithId != null) {
return controllerWithId;
}
}
return null;
@@ -254,8 +300,8 @@ public class Router {
* @return The matching Controller, if one exists
*/
public Controller getControllerWithTag(String tag) {
for (ControllerTransaction transaction : mBackStack) {
if (tag.equals(transaction.tag)) {
for (RouterTransaction transaction : backstack) {
if (tag.equals(transaction.tag())) {
return transaction.controller;
}
}
@@ -266,7 +312,74 @@ public class Router {
* Returns the number of {@link Controller}s currently in the backstack
*/
public int getBackstackSize() {
return mBackStack.size();
return backstack.size();
}
/**
* Returns the current backstack, ordered from root to most recently pushed.
*/
public List<RouterTransaction> getBackstack() {
List<RouterTransaction> list = new ArrayList<>();
Iterator<RouterTransaction> backstackIterator = backstack.reverseIterator();
while (backstackIterator.hasNext()) {
list.add(backstackIterator.next());
}
return list;
}
/**
* Sets the backstack, transitioning from the current top controller to the top of the new stack (if different)
* using the passed {@link ControllerChangeHandler}
*
* @param newBackstack The new backstack
* @param changeHandler An optional change handler to be used to handle the root view of transition
*/
public void setBackstack(@NonNull List<RouterTransaction> newBackstack, ControllerChangeHandler changeHandler) {
List<RouterTransaction> oldVisibleTransactions = getVisibleTransactions(backstack.iterator());
removeAllExceptVisibleAndUnowned();
if (newBackstack.size() > 0) {
List<RouterTransaction> reverseNewBackstack = new ArrayList<>(newBackstack);
Collections.reverse(reverseNewBackstack);
List<RouterTransaction> newVisibleTransactions = getVisibleTransactions(reverseNewBackstack.iterator());
boolean visibleTransactionsChanged = newVisibleTransactions.size() != oldVisibleTransactions.size();
if (!visibleTransactionsChanged) {
for (int i = 0; i < oldVisibleTransactions.size(); i++) {
if (oldVisibleTransactions.get(i).controller != newVisibleTransactions.get(i).controller) {
visibleTransactionsChanged = true;
break;
}
}
}
if (visibleTransactionsChanged) {
ControllerChangeHandler handler = changeHandler != null ? changeHandler : new SimpleSwapChangeHandler();
Controller rootController = oldVisibleTransactions.size() > 0 ? oldVisibleTransactions.get(0).controller : null;
performControllerChange(newVisibleTransactions.get(0).controller, rootController, true, handler.copy());
for (int i = oldVisibleTransactions.size() - 1; i > 0; i--) {
RouterTransaction transaction = oldVisibleTransactions.get(i);
ControllerChangeHandler localHandler = handler.copy();
localHandler.setForceRemoveViewOnPush(true);
performControllerChange(null, transaction.controller, true, localHandler);
}
for (int i = 1; i < newVisibleTransactions.size(); i++) {
RouterTransaction transaction = newVisibleTransactions.get(i);
handler = transaction.pushChangeHandler() != null ? transaction.pushChangeHandler().copy() : new SimpleSwapChangeHandler();
performControllerChange(transaction.controller, newVisibleTransactions.get(i - 1).controller, true, handler.copy());
}
}
}
for (RouterTransaction transaction : backstack) {
transaction.onAttachedToRouter();
}
backstack.setBackstack(newBackstack);
}
/**
@@ -282,8 +395,8 @@ public class Router {
* @param changeListener The listener
*/
public void addChangeListener(ControllerChangeListener changeListener) {
if (!mChangeListeners.contains(changeListener)) {
mChangeListeners.add(changeListener);
if (!changeListeners.contains(changeListener)) {
changeListeners.add(changeListener);
}
}
@@ -293,14 +406,14 @@ public class Router {
* @param changeListener The listener to be removed
*/
public void removeChangeListener(ControllerChangeListener changeListener) {
mChangeListeners.remove(changeListener);
changeListeners.remove(changeListener);
}
/**
* Attaches this Router's existing backstack to its container if one exists.
*/
void rebindIfNeeded() {
Iterator<RouterTransaction> backstackIterator = mBackStack.reverseIterator();
public void rebindIfNeeded() {
Iterator<RouterTransaction> backstackIterator = backstack.reverseIterator();
while (backstackIterator.hasNext()) {
RouterTransaction transaction = backstackIterator.next();
@@ -310,83 +423,175 @@ public class Router {
}
}
public final void onActivityResult(String instanceId, int requestCode, int resultCode, Intent data) {
Controller controller = getControllerWithInstanceId(instanceId);
if (controller != null) {
controller.onActivityResult(requestCode, resultCode, data);
}
}
public final void onActivityStarted(Activity activity) {
for (RouterTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
transaction.controller.activityStarted(activity);
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onActivityStarted(activity);
}
}
}
public final void onActivityResumed(Activity activity) {
for (RouterTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
transaction.controller.activityResumed(activity);
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onActivityResumed(activity);
}
}
}
public final void onActivityPaused(Activity activity) {
for (RouterTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
transaction.controller.activityPaused(activity);
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onActivityPaused(activity);
}
}
}
public final void onActivityStopped(Activity activity) {
for (RouterTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
transaction.controller.activityStopped(activity);
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onActivityStopped(activity);
}
}
}
public final void onActivitySaveInstanceState(Activity activity, Bundle outState) {
mBackStack.saveInstanceState(outState);
}
public void onActivityDestroyed(Activity activity) {
prepareForContainerRemoval();
changeListeners.clear();
public final void onActivityDestroyed(Activity activity) {
mContainer.setOnHierarchyChangeListener(null);
mLifecycleHandler = null;
mContainer = null;
mChangeListeners.clear();
for (RouterTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
transaction.controller.activityDestroyed(activity.isChangingConfigurations());
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onActivityDestroyed(activity);
}
}
for (int index = destroyingControllers.size() - 1; index >= 0; index--) {
Controller controller = destroyingControllers.get(index);
controller.activityDestroyed(activity.isChangingConfigurations());
for (Router childRouter : controller.getChildRouters()) {
childRouter.onActivityDestroyed(activity);
}
}
container = null;
}
public void prepareForHostDetach() {
for (RouterTransaction transaction : backstack) {
if (ControllerChangeHandler.completePushImmediately(transaction.controller.getInstanceId())) {
transaction.controller.setNeedsAttach();
}
transaction.controller.prepareForHostDetach();
}
}
public final void onRestoreInstanceState(Bundle savedInstanceState) {
mBackStack.restoreInstanceState(savedInstanceState);
public void saveInstanceState(Bundle outState) {
prepareForHostDetach();
Bundle backstackState = new Bundle();
backstack.saveInstanceState(backstackState);
outState.putParcelable(KEY_BACKSTACK, backstackState);
outState.putBoolean(KEY_POPS_LAST_VIEW, popsLastView);
}
public void restoreInstanceState(Bundle savedInstanceState) {
Bundle backstackBundle = savedInstanceState.getParcelable(KEY_BACKSTACK);
backstack.restoreInstanceState(backstackBundle);
popsLastView = savedInstanceState.getBoolean(KEY_POPS_LAST_VIEW);
Iterator<RouterTransaction> backstackIterator = backstack.reverseIterator();
while (backstackIterator.hasNext()) {
setControllerRouter(backstackIterator.next().controller);
}
}
public final void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
for (RouterTransaction transaction : backstack) {
transaction.controller.createOptionsMenu(menu, inflater);
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onCreateOptionsMenu(menu, inflater);
}
}
}
public final void onPrepareOptionsMenu(Menu menu) {
for (RouterTransaction transaction : backstack) {
transaction.controller.prepareOptionsMenu(menu);
for (Router childRouter : transaction.controller.getChildRouters()) {
childRouter.onPrepareOptionsMenu(menu);
}
}
}
public final boolean onOptionsItemSelected(MenuItem item) {
for (RouterTransaction transaction : backstack) {
if (transaction.controller.optionsItemSelected(item)) {
return true;
}
for (Router childRouter : transaction.controller.getChildRouters()) {
if (childRouter.onOptionsItemSelected(item)) {
return true;
}
}
}
return false;
}
private void popToTransaction(@NonNull RouterTransaction transaction, ControllerChangeHandler changeHandler) {
RouterTransaction topTransaction = mBackStack.peek();
List<RouterTransaction> poppedTransactions = mBackStack.popTo(transaction);
RouterTransaction topTransaction = backstack.peek();
List<RouterTransaction> poppedTransactions = backstack.popTo(transaction);
trackDestroyingControllers(poppedTransactions);
if (poppedTransactions.size() > 0) {
if (changeHandler == null) {
changeHandler = topTransaction.getPopControllerChangeHandler();
changeHandler = topTransaction.popChangeHandler();
}
performControllerChange(mBackStack.peek().controller, topTransaction.controller, false, changeHandler);
performControllerChange(backstack.peek().controller, topTransaction.controller, false, changeHandler);
}
}
public final void setHost(@NonNull LifecycleHandler lifecycleHandler, @NonNull ViewGroup container) {
if (mLifecycleHandler != lifecycleHandler || mContainer != container) {
if (mContainer != null && mContainer instanceof ControllerChangeListener) {
removeChangeListener((ControllerChangeListener)mContainer);
}
if (container instanceof ControllerChangeListener) {
addChangeListener((ControllerChangeListener)container);
}
mLifecycleHandler = lifecycleHandler;
mContainer = container;
void prepareForContainerRemoval() {
if (container != null) {
container.setOnHierarchyChangeListener(null);
}
}
final LifecycleHandler getLifecycleHandler() {
return mLifecycleHandler;
final List<Controller> getControllers() {
List<Controller> controllers = new ArrayList<>();
Iterator<RouterTransaction> backstackIterator = backstack.reverseIterator();
while (backstackIterator.hasNext()) {
controllers.add(backstackIterator.next().controller);
}
return controllers;
}
public final Boolean handleRequestedPermission(@NonNull String permission) {
for (ControllerTransaction transaction : mBackStack) {
for (RouterTransaction transaction : backstack) {
if (transaction.controller.didRequestPermission(permission)) {
return transaction.controller.shouldShowRequestPermissionRationale(permission);
}
@@ -395,12 +600,16 @@ public class Router {
}
private void performControllerChange(RouterTransaction to, RouterTransaction from, boolean isPush) {
if (isPush && to != null) {
to.onAttachedToRouter();
}
ControllerChangeHandler changeHandler;
if (isPush) {
//noinspection ConstantConditions
changeHandler = to.getPushControllerChangeHandler();
changeHandler = to.pushChangeHandler();
} else if (from != null) {
changeHandler = from.getPopControllerChangeHandler();
changeHandler = from.popChangeHandler();
} else {
changeHandler = new SimpleSwapChangeHandler();
}
@@ -413,21 +622,102 @@ public class Router {
private void performControllerChange(final Controller to, final Controller from, boolean isPush, @NonNull ControllerChangeHandler changeHandler) {
if (to != null) {
to.setRouter(this);
} else if (mBackStack.size() == 0) {
setControllerRouter(to);
} else if (backstack.size() == 0 && !popsLastView) {
// We're emptying out the backstack. Views get weird if you transition them out, so just no-op it. The hosting
// Activity should be handling this by finishing or at least hiding this view.
changeHandler = new NoOpControllerChangeHandler();
}
if (mContainer != null) {
ControllerChangeHandler.executeChange(to, from, isPush, mContainer, changeHandler, mChangeListeners);
}
ControllerChangeHandler.executeChange(to, from, isPush, container, changeHandler, changeListeners);
}
private void pushToBackstack(@NonNull RouterTransaction entry) {
mBackStack.push(entry);
backstack.push(entry);
}
private void trackDestroyingController(RouterTransaction transaction) {
if (!transaction.controller.isDestroyed()) {
destroyingControllers.add(transaction.controller);
transaction.controller.addLifecycleListener(new LifecycleListener() {
@Override
public void postDestroy(@NonNull Controller controller) {
destroyingControllers.remove(controller);
}
});
}
}
private void trackDestroyingControllers(List<RouterTransaction> transactions) {
for (RouterTransaction transaction : transactions) {
trackDestroyingController(transaction);
}
}
private void removeAllExceptVisibleAndUnowned() {
List<View> views = new ArrayList<>();
for (RouterTransaction transaction : getVisibleTransactions(backstack.iterator())) {
if (transaction.controller.getView() != null) {
views.add(transaction.controller.getView());
}
}
for (Router router : getSiblingRouters()) {
if (router.container == container) {
addRouterViewsToList(router, views);
}
}
final int childCount = container.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = container.getChildAt(i);
if (!views.contains(child)) {
container.removeView(child);
}
}
}
private void addRouterViewsToList(Router router, List<View> list) {
for (Controller controller : router.getControllers()) {
if (controller.getView() != null) {
list.add(controller.getView());
}
for (Router child : controller.getChildRouters()) {
addRouterViewsToList(child, list);
}
}
}
private List<RouterTransaction> getVisibleTransactions(Iterator<RouterTransaction> backstackIterator) {
List<RouterTransaction> transactions = new ArrayList<>();
while (backstackIterator.hasNext()) {
RouterTransaction transaction = backstackIterator.next();
transactions.add(transaction);
if (transaction.pushChangeHandler() == null || transaction.pushChangeHandler().removesFromViewOnPush()) {
break;
}
}
Collections.reverse(transactions);
return transactions;
}
void setControllerRouter(Controller controller) {
controller.setRouter(this);
}
abstract void invalidateOptionsMenu();
abstract void startActivity(Intent intent);
abstract void startActivityForResult(String instanceId, Intent intent, int requestCode);
abstract void startActivityForResult(String instanceId, Intent intent, int requestCode, Bundle options);
abstract void registerForActivityResult(String instanceId, int requestCode);
abstract void unregisterForActivityResults(String instanceId);
abstract void requestPermissions(String instanceId, String[] permissions, int requestCode);
abstract boolean hasHost();
abstract List<Router> getSiblingRouters();
abstract Router getRootRouter();
}
@@ -4,41 +4,113 @@ import android.os.Bundle;
import android.support.annotation.NonNull;
/**
* A {@link ControllerTransaction} implementation used for adding {@link Controller}s to a {@link Router}.
* Metadata used for adding {@link Controller}s to a {@link Router}.
*/
public class RouterTransaction extends ControllerTransaction {
public class RouterTransaction {
private RouterTransaction(Builder builder) {
super(builder);
private static final String KEY_VIEW_CONTROLLER_BUNDLE = "RouterTransaction.controller.bundle";
private static final String KEY_PUSH_TRANSITION = "RouterTransaction.pushControllerChangeHandler";
private static final String KEY_POP_TRANSITION = "RouterTransaction.popControllerChangeHandler";
private static final String KEY_TAG = "RouterTransaction.tag";
private static final String KEY_ATTACHED_TO_ROUTER = "RouterTransaction.attachedToRouter";
@NonNull final Controller controller;
private String tag;
private ControllerChangeHandler pushControllerChangeHandler;
private ControllerChangeHandler popControllerChangeHandler;
private boolean attachedToRouter;
public static RouterTransaction with(@NonNull Controller controller) {
return new RouterTransaction(controller);
}
private RouterTransaction(@NonNull Controller controller) {
this.controller = controller;
}
RouterTransaction(@NonNull Bundle bundle) {
super(bundle);
controller = Controller.newInstance(bundle.getBundle(KEY_VIEW_CONTROLLER_BUNDLE));
pushControllerChangeHandler = ControllerChangeHandler.fromBundle(bundle.getBundle(KEY_PUSH_TRANSITION));
popControllerChangeHandler = ControllerChangeHandler.fromBundle(bundle.getBundle(KEY_POP_TRANSITION));
tag = bundle.getString(KEY_TAG);
attachedToRouter = bundle.getBoolean(KEY_ATTACHED_TO_ROUTER);
}
void onAttachedToRouter() {
attachedToRouter = true;
}
public Controller controller() {
return controller;
}
public String tag() {
return tag;
}
public RouterTransaction tag(String tag) {
if (!attachedToRouter) {
this.tag = tag;
return this;
} else {
throw new RuntimeException(getClass().getSimpleName() + "s can not be modified after being added to a Router.");
}
}
public ControllerChangeHandler pushChangeHandler() {
ControllerChangeHandler handler = controller.getOverriddenPushHandler();
if (handler == null) {
handler = pushControllerChangeHandler;
}
return handler;
}
public RouterTransaction pushChangeHandler(ControllerChangeHandler handler) {
if (!attachedToRouter) {
pushControllerChangeHandler = handler;
return this;
} else {
throw new RuntimeException(getClass().getSimpleName() + "s can not be modified after being added to a Router.");
}
}
public ControllerChangeHandler popChangeHandler() {
ControllerChangeHandler handler = controller.getOverriddenPopHandler();
if (handler == null) {
handler = popControllerChangeHandler;
}
return handler;
}
public RouterTransaction popChangeHandler(ControllerChangeHandler handler) {
if (!attachedToRouter) {
popControllerChangeHandler = handler;
return this;
} else {
throw new RuntimeException(getClass().getSimpleName() + "s can not be modified after being added to a Router.");
}
}
/**
* Creates a new Builder
*
* @param controller The {@link Controller} to add to the {@link Router}
* Used to serialize this transaction into a Bundle
*/
public static Builder builder(@NonNull Controller controller) {
return new Builder(controller);
}
public Bundle saveInstanceState() {
Bundle bundle = new Bundle();
/**
* A {@link ControllerTransaction.Builder} implementation used for adding {@link Controller}s to a {@link Router}.
*/
public static class Builder extends ControllerTransaction.Builder<Builder> {
bundle.putBundle(KEY_VIEW_CONTROLLER_BUNDLE, controller.saveInstanceState());
Builder(@NonNull Controller controller) {
super(controller);
if (pushControllerChangeHandler != null) {
bundle.putBundle(KEY_PUSH_TRANSITION, pushControllerChangeHandler.toBundle());
}
if (popControllerChangeHandler != null) {
bundle.putBundle(KEY_POP_TRANSITION, popControllerChangeHandler.toBundle());
}
/** Creates the transaction */
public RouterTransaction build() {
return new RouterTransaction(this);
}
bundle.putString(KEY_TAG, tag);
bundle.putBoolean(KEY_ATTACHED_TO_ROUTER, attachedToRouter);
return bundle;
}
}
@@ -8,6 +8,7 @@ import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.ControllerChangeHandler;
/**
@@ -20,8 +21,11 @@ public abstract class AnimatorChangeHandler extends ControllerChangeHandler {
public static final long DEFAULT_ANIMATION_DURATION = -1;
private long mAnimationDuration;
private boolean mRemovesFromViewOnPush;
private long animationDuration;
private boolean removesFromViewOnPush;
private boolean canceled;
private boolean needsImmediateCompletion;
private Animator animator;
public AnimatorChangeHandler() {
this(DEFAULT_ANIMATION_DURATION, true);
@@ -36,30 +40,51 @@ public abstract class AnimatorChangeHandler extends ControllerChangeHandler {
}
public AnimatorChangeHandler(long duration, boolean removesFromViewOnPush) {
mAnimationDuration = duration;
mRemovesFromViewOnPush = removesFromViewOnPush;
animationDuration = duration;
this.removesFromViewOnPush = removesFromViewOnPush;
}
@Override
public void saveToBundle(@NonNull Bundle bundle) {
super.saveToBundle(bundle);
bundle.putLong(KEY_DURATION, mAnimationDuration);
bundle.putBoolean(KEY_REMOVES_FROM_ON_PUSH, mRemovesFromViewOnPush);
bundle.putLong(KEY_DURATION, animationDuration);
bundle.putBoolean(KEY_REMOVES_FROM_ON_PUSH, removesFromViewOnPush);
}
@Override
public void restoreFromBundle(@NonNull Bundle bundle) {
super.restoreFromBundle(bundle);
mAnimationDuration = bundle.getLong(KEY_DURATION);
mRemovesFromViewOnPush = bundle.getBoolean(KEY_REMOVES_FROM_ON_PUSH);
animationDuration = bundle.getLong(KEY_DURATION);
removesFromViewOnPush = bundle.getBoolean(KEY_REMOVES_FROM_ON_PUSH);
}
@Override
public void onAbortPush(@NonNull ControllerChangeHandler newHandler, Controller newTop) {
super.onAbortPush(newHandler, newTop);
canceled = true;
if (animator != null) {
animator.cancel();
}
}
@Override
public void completeImmediately() {
super.completeImmediately();
needsImmediateCompletion = true;
if (animator != null) {
animator.cancel();
}
}
public long getAnimationDuration() {
return mAnimationDuration;
return animationDuration;
}
@Override
public boolean removesFromViewOnPush() {
return mRemovesFromViewOnPush;
return removesFromViewOnPush;
}
/**
@@ -86,7 +111,7 @@ public abstract class AnimatorChangeHandler extends ControllerChangeHandler {
if (addingToView) {
if (isPush || from == null) {
container.addView(to);
} else {
} else if (to.getParent() == null) {
container.addView(to, container.indexOfChild(from));
}
@@ -111,27 +136,49 @@ public abstract class AnimatorChangeHandler extends ControllerChangeHandler {
}
}
private void performAnimation(@NonNull final ViewGroup container, final View from, View to, final boolean isPush, final boolean toAddedToContainer, @NonNull final ControllerChangeCompletedListener changeListener) {
Animator animator = getAnimator(container, from, to, isPush, toAddedToContainer);
private void performAnimation(@NonNull final ViewGroup container, final View from, final View to, final boolean isPush, final boolean toAddedToContainer, @NonNull final ControllerChangeCompletedListener changeListener) {
if (canceled) {
changeListener.onChangeCompleted();
return;
}
if (mAnimationDuration > 0) {
animator.setDuration(mAnimationDuration);
animator = getAnimator(container, from, to, isPush, toAddedToContainer);
if (animationDuration > 0) {
animator.setDuration(animationDuration);
}
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (from != null && (!isPush || mRemovesFromViewOnPush)) {
public void onAnimationCancel(Animator animation) {
if (from != null && (!isPush || removesFromViewOnPush) && needsImmediateCompletion) {
container.removeView(from);
}
changeListener.onChangeCompleted();
animator.removeListener(this);
animator = null;
}
if (isPush && from != null) {
resetFromView(from);
@Override
public void onAnimationEnd(Animator animation) {
if (!canceled && animator != null) {
if (from != null && (!isPush || removesFromViewOnPush)) {
container.removeView(from);
}
changeListener.onChangeCompleted();
animator.removeListener(this);
if (isPush && from != null) {
resetFromView(from);
}
animator = null;
}
}
});
animator.start();
}
@@ -51,6 +51,6 @@ public class HorizontalChangeHandler extends AnimatorChangeHandler {
@Override
protected void resetFromView(@NonNull View from) {
from.setTranslationY(0);
from.setTranslationX(0);
}
}
@@ -6,57 +6,99 @@ import android.view.View;
import android.view.View.OnAttachStateChangeListener;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.ControllerChangeHandler;
/**
* A {@link ControllerChangeHandler} that will instantly swap Views with no animations or transitions.
*/
public class SimpleSwapChangeHandler extends ControllerChangeHandler {
public class SimpleSwapChangeHandler extends ControllerChangeHandler implements OnAttachStateChangeListener {
private static final String KEY_REMOVES_FROM_ON_PUSH = "SimpleSwapChangeHandler.removesFromViewOnPush";
private boolean mRemovesFromViewOnPush;
private boolean removesFromViewOnPush;
private boolean canceled;
private ViewGroup container;
private ControllerChangeCompletedListener changeListener;
public SimpleSwapChangeHandler() {
this(true);
}
public SimpleSwapChangeHandler(boolean removesFromViewOnPush) {
mRemovesFromViewOnPush = removesFromViewOnPush;
this.removesFromViewOnPush = removesFromViewOnPush;
}
@Override
public void saveToBundle(@NonNull Bundle bundle) {
super.saveToBundle(bundle);
bundle.putBoolean(KEY_REMOVES_FROM_ON_PUSH, mRemovesFromViewOnPush);
bundle.putBoolean(KEY_REMOVES_FROM_ON_PUSH, removesFromViewOnPush);
}
@Override
public void restoreFromBundle(@NonNull Bundle bundle) {
super.restoreFromBundle(bundle);
mRemovesFromViewOnPush = bundle.getBoolean(KEY_REMOVES_FROM_ON_PUSH);
removesFromViewOnPush = bundle.getBoolean(KEY_REMOVES_FROM_ON_PUSH);
}
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull final ControllerChangeCompletedListener changeListener) {
if (from != null && (!isPush || mRemovesFromViewOnPush)) {
container.removeView(from);
}
public void onAbortPush(@NonNull ControllerChangeHandler newHandler, Controller newTop) {
super.onAbortPush(newHandler, newTop);
if (to != null && to.getParent() == null) {
to.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
view.removeOnAttachStateChangeListener(this);
changeListener.onChangeCompleted();
}
canceled = true;
}
@Override
public void onViewDetachedFromWindow(View v) { }
});
@Override
public void completeImmediately() {
if (changeListener != null) {
changeListener.onChangeCompleted();
changeListener = null;
container.addView(to);
container.removeOnAttachStateChangeListener(this);
container = null;
}
}
}
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
if (!canceled) {
if (from != null && (!isPush || removesFromViewOnPush)) {
container.removeView(from);
}
if (to != null && to.getParent() == null) {
container.addView(to);
}
}
if (container.getWindowToken() != null) {
changeListener.onChangeCompleted();
} else {
this.changeListener = changeListener;
this.container = container;
container.addOnAttachStateChangeListener(this);
}
}
@Override
public boolean removesFromViewOnPush() {
return removesFromViewOnPush;
}
@Override
public void onViewAttachedToWindow(View v) {
v.removeOnAttachStateChangeListener(this);
if (changeListener != null) {
changeListener.onChangeCompleted();
changeListener = null;
container = null;
}
}
@Override
public void onViewDetachedFromWindow(View v) { }
}
@@ -9,6 +9,7 @@ import android.transition.TransitionManager;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.ControllerChangeHandler;
/**
@@ -17,6 +18,8 @@ import com.bluelinelabs.conductor.ControllerChangeHandler;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public abstract class TransitionChangeHandler extends ControllerChangeHandler {
private boolean canceled;
/**
* Should be overridden to return the Transition to use while replacing Views.
*
@@ -28,8 +31,20 @@ public abstract class TransitionChangeHandler extends ControllerChangeHandler {
@NonNull
protected abstract Transition getTransition(@NonNull ViewGroup container, View from, View to, boolean isPush);
@Override
public void onAbortPush(@NonNull ControllerChangeHandler newHandler, Controller newTop) {
super.onAbortPush(newHandler, newTop);
canceled = true;
}
@Override
public void performChange(@NonNull final ViewGroup container, View from, View to, boolean isPush, @NonNull final ControllerChangeCompletedListener changeListener) {
if (canceled) {
changeListener.onChangeCompleted();
return;
}
Transition transition = getTransition(container, from, to, isPush);
transition.addListener(new TransitionListener() {
@Override
@@ -61,4 +76,8 @@ public abstract class TransitionChangeHandler extends ControllerChangeHandler {
}
}
@Override
public final boolean removesFromViewOnPush() {
return true;
}
}
@@ -20,8 +20,8 @@ public class TransitionChangeHandlerCompat extends ControllerChangeHandler {
private static final String KEY_TRANSITION_HANDLER_STATE = "TransitionChangeHandlerCompat.transitionChangeHandler.state";
private static final String KEY_FALLBACK_HANDLER_STATE = "TransitionChangeHandlerCompat.fallbackChangeHandler.state";
private TransitionChangeHandler mTransitionChangeHandler;
private ControllerChangeHandler mFallbackChangeHandler;
private TransitionChangeHandler transitionChangeHandler;
private ControllerChangeHandler fallbackChangeHandler;
public TransitionChangeHandlerCompat() { }
@@ -33,16 +33,16 @@ public class TransitionChangeHandlerCompat extends ControllerChangeHandler {
* @param fallbackChangeHandler The change handler that will be used on APIs below 21
*/
public TransitionChangeHandlerCompat(TransitionChangeHandler transitionChangeHandler, ControllerChangeHandler fallbackChangeHandler) {
mTransitionChangeHandler = transitionChangeHandler;
mFallbackChangeHandler = fallbackChangeHandler;
this.transitionChangeHandler = transitionChangeHandler;
this.fallbackChangeHandler = fallbackChangeHandler;
}
@Override
public void performChange(@NonNull final ViewGroup container, View from, View to, boolean isPush, @NonNull final ControllerChangeCompletedListener changeListener) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mTransitionChangeHandler.performChange(container, from, to, isPush, changeListener);
transitionChangeHandler.performChange(container, from, to, isPush, changeListener);
} else {
mFallbackChangeHandler.performChange(container, from, to, isPush, changeListener);
fallbackChangeHandler.performChange(container, from, to, isPush, changeListener);
}
}
@@ -50,15 +50,15 @@ public class TransitionChangeHandlerCompat extends ControllerChangeHandler {
public void saveToBundle(@NonNull Bundle bundle) {
super.saveToBundle(bundle);
bundle.putString(KEY_TRANSITION_HANDLER_CLASS, mTransitionChangeHandler.getClass().getCanonicalName());
bundle.putString(KEY_FALLBACK_HANDLER_CLASS, mFallbackChangeHandler.getClass().getCanonicalName());
bundle.putString(KEY_TRANSITION_HANDLER_CLASS, transitionChangeHandler.getClass().getName());
bundle.putString(KEY_FALLBACK_HANDLER_CLASS, fallbackChangeHandler.getClass().getName());
Bundle transitionBundle = new Bundle();
mTransitionChangeHandler.saveToBundle(transitionBundle);
transitionChangeHandler.saveToBundle(transitionBundle);
bundle.putBundle(KEY_TRANSITION_HANDLER_STATE, transitionBundle);
Bundle fallbackBundle = new Bundle();
mFallbackChangeHandler.saveToBundle(fallbackBundle);
fallbackChangeHandler.saveToBundle(fallbackBundle);
bundle.putBundle(KEY_FALLBACK_HANDLER_STATE, fallbackBundle);
}
@@ -67,14 +67,22 @@ public class TransitionChangeHandlerCompat extends ControllerChangeHandler {
super.restoreFromBundle(bundle);
String transitionClassName = bundle.getString(KEY_TRANSITION_HANDLER_CLASS);
mTransitionChangeHandler = ClassUtils.newInstance(transitionClassName);
transitionChangeHandler = ClassUtils.newInstance(transitionClassName);
//noinspection ConstantConditions
mTransitionChangeHandler.restoreFromBundle(bundle.getBundle(KEY_TRANSITION_HANDLER_STATE));
transitionChangeHandler.restoreFromBundle(bundle.getBundle(KEY_TRANSITION_HANDLER_STATE));
String fallbackClassName = bundle.getString(KEY_FALLBACK_HANDLER_CLASS);
mFallbackChangeHandler = ClassUtils.newInstance(fallbackClassName);
fallbackChangeHandler = ClassUtils.newInstance(fallbackClassName);
//noinspection ConstantConditions
mFallbackChangeHandler.restoreFromBundle(bundle.getBundle(KEY_FALLBACK_HANDLER_STATE));
fallbackChangeHandler.restoreFromBundle(bundle.getBundle(KEY_FALLBACK_HANDLER_STATE));
}
@Override
public boolean removesFromViewOnPush() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return transitionChangeHandler.removesFromViewOnPush();
} else {
return fallbackChangeHandler.removesFromViewOnPush();
}
}
}
@@ -4,16 +4,23 @@ import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.ActivityHostedRouter;
import com.bluelinelabs.conductor.Router;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LifecycleHandler extends Fragment implements ActivityLifecycleCallbacks {
@@ -22,17 +29,20 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
private static final String KEY_PERMISSION_REQUEST_CODES = "LifecycleHandler.permissionRequests";
private static final String KEY_ACTIVITY_REQUEST_CODES = "LifecycleHandler.activityRequests";
private static final String KEY_ROUTER_STATE_PREFIX = "LifecycleHandler.routerState";
private Activity mActivity;
private boolean mHasRegisteredCallbacks;
private Activity activity;
private boolean hasRegisteredCallbacks;
private boolean destroyed;
private SparseArray<String> mPermissionRequestMap = new SparseArray<>();
private SparseArray<String> mActivityRequestMap = new SparseArray<>();
private SparseArray<String> permissionRequestMap = new SparseArray<>();
private SparseArray<String> activityRequestMap = new SparseArray<>();
private final Map<Integer, Router> mRouterMap = new HashMap<>();
private final Map<Integer, ActivityHostedRouter> routerMap = new HashMap<>();
public LifecycleHandler() {
setRetainInstance(true);
setHasOptionsMenu(true);
}
private static LifecycleHandler findInActivity(Activity activity) {
@@ -54,21 +64,31 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
}
public Router getRouter(ViewGroup container, Bundle savedInstanceState) {
Router router = mRouterMap.get(getRouterHashKey(container));
ActivityHostedRouter router = routerMap.get(getRouterHashKey(container));
if (router == null) {
router = new Router();
router = new ActivityHostedRouter();
router.setHost(this, container);
if (savedInstanceState != null) {
router.onRestoreInstanceState(savedInstanceState);
Bundle routerSavedState = savedInstanceState.getBundle(KEY_ROUTER_STATE_PREFIX + router.getContainerId());
if (routerSavedState != null) {
router.restoreInstanceState(routerSavedState);
}
}
mRouterMap.put(getRouterHashKey(container), router);
routerMap.put(getRouterHashKey(container), router);
} else {
router.setHost(this, container);
}
router.setHost(this, container);
return router;
}
public List<Router> getRouters() {
return new ArrayList<Router>(routerMap.values());
}
public Activity getLifecycleActivity() {
return mActivity;
return activity;
}
private static int getRouterHashKey(ViewGroup viewGroup) {
@@ -76,10 +96,10 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
}
private void registerActivityListener(Activity activity) {
mActivity = activity;
this.activity = activity;
if (!mHasRegisteredCallbacks) {
mHasRegisteredCallbacks = true;
if (!hasRegisteredCallbacks) {
hasRegisteredCallbacks = true;
activity.getApplication().registerActivityLifecycleCallbacks(this);
}
}
@@ -90,10 +110,10 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
if (savedInstanceState != null) {
StringSparseArrayParceler permissionParcel = savedInstanceState.getParcelable(KEY_PERMISSION_REQUEST_CODES);
mPermissionRequestMap = permissionParcel != null ? permissionParcel.getStringSparseArray() : null;
permissionRequestMap = permissionParcel != null ? permissionParcel.getStringSparseArray() : null;
StringSparseArrayParceler activityParcel = savedInstanceState.getParcelable(KEY_ACTIVITY_REQUEST_CODES);
mActivityRequestMap = activityParcel != null ? activityParcel.getStringSparseArray() : null;
activityRequestMap = activityParcel != null ? activityParcel.getStringSparseArray() : null;
}
}
@@ -101,22 +121,50 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_PERMISSION_REQUEST_CODES, new StringSparseArrayParceler(mPermissionRequestMap));
outState.putParcelable(KEY_ACTIVITY_REQUEST_CODES, new StringSparseArrayParceler(mActivityRequestMap));
outState.putParcelable(KEY_PERMISSION_REQUEST_CODES, new StringSparseArrayParceler(permissionRequestMap));
outState.putParcelable(KEY_ACTIVITY_REQUEST_CODES, new StringSparseArrayParceler(activityRequestMap));
}
@Override
public void onDestroy() {
super.onDestroy();
if (mActivity != null) {
mActivity.getApplication().unregisterActivityLifecycleCallbacks(this);
if (activity != null) {
activity.getApplication().unregisterActivityLifecycleCallbacks(this);
destroyRouters();
activity = null;
}
}
for (Router router : mRouterMap.values()) {
router.onActivityDestroyed(mActivity);
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
destroyed = false;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
destroyed = false;
}
@Override
public void onDetach() {
super.onDetach();
destroyRouters();
}
private void destroyRouters() {
if (!destroyed) {
destroyed = true;
if (activity != null) {
for (Router router : routerMap.values()) {
router.onActivityDestroyed(activity);
}
}
mActivity = null;
}
}
@@ -124,9 +172,9 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String instanceId = mActivityRequestMap.get(requestCode);
String instanceId = activityRequestMap.get(requestCode);
if (instanceId != null) {
for (Router router : mRouterMap.values()) {
for (Router router : routerMap.values()) {
router.onActivityResult(instanceId, requestCode, resultCode, data);
}
}
@@ -136,9 +184,9 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
String instanceId = mPermissionRequestMap.get(requestCode);
String instanceId = permissionRequestMap.get(requestCode);
if (instanceId != null) {
for (Router router : mRouterMap.values()) {
for (Router router : routerMap.values()) {
router.onRequestPermissionsResult(instanceId, requestCode, permissions, grantResults);
}
}
@@ -146,7 +194,7 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
@Override
public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
for (Router router : mRouterMap.values()) {
for (Router router : routerMap.values()) {
Boolean handled = router.handleRequestedPermission(permission);
if (handled != null) {
return handled;
@@ -155,33 +203,74 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
return super.shouldShowRequestPermissionRationale(permission);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
for (Router router : routerMap.values()) {
router.onCreateOptionsMenu(menu, inflater);
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
for (Router router : routerMap.values()) {
router.onPrepareOptionsMenu(menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
for (Router router : routerMap.values()) {
if (router.onOptionsItemSelected(item)) {
return true;
}
}
return super.onOptionsItemSelected(item);
}
public void registerForActivityResult(String instanceId, int requestCode) {
activityRequestMap.put(requestCode, instanceId);
}
public void unregisterForActivityResults(String instanceId) {
for (int i = activityRequestMap.size() - 1; i >= 0; i--) {
if (instanceId.equals(activityRequestMap.get(activityRequestMap.keyAt(i)))) {
activityRequestMap.removeAt(i);
}
}
}
public void startActivityForResult(String instanceId, Intent intent, int requestCode) {
mActivityRequestMap.put(requestCode, instanceId);
registerForActivityResult(instanceId, requestCode);
startActivityForResult(intent, requestCode);
}
public void startActivityForResult(String instanceId, Intent intent, int requestCode, Bundle options) {
mActivityRequestMap.put(requestCode, instanceId);
registerForActivityResult(instanceId, requestCode);
startActivityForResult(intent, requestCode, options);
}
@TargetApi(Build.VERSION_CODES.M)
public void requestPermissions(String instanceId, String[] permissions, int requestCode) {
mPermissionRequestMap.put(requestCode, instanceId);
permissionRequestMap.put(requestCode, instanceId);
requestPermissions(permissions, requestCode);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (mActivity == null && findInActivity(activity) == LifecycleHandler.this) {
mActivity = activity;
if (this.activity == null && findInActivity(activity) == LifecycleHandler.this) {
this.activity = activity;
}
}
@Override
public void onActivityStarted(Activity activity) {
if (mActivity == activity) {
for (Router router : mRouterMap.values()) {
if (this.activity == activity) {
for (Router router : routerMap.values()) {
router.onActivityStarted(activity);
}
}
@@ -189,8 +278,8 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
@Override
public void onActivityResumed(Activity activity) {
if (mActivity == activity) {
for (Router router : mRouterMap.values()) {
if (this.activity == activity) {
for (Router router : routerMap.values()) {
router.onActivityResumed(activity);
}
}
@@ -198,8 +287,8 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
@Override
public void onActivityPaused(Activity activity) {
if (mActivity == activity) {
for (Router router : mRouterMap.values()) {
if (this.activity == activity) {
for (Router router : routerMap.values()) {
router.onActivityPaused(activity);
}
}
@@ -207,8 +296,8 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
@Override
public void onActivityStopped(Activity activity) {
if (mActivity == activity) {
for (Router router : mRouterMap.values()) {
if (this.activity == activity) {
for (Router router : routerMap.values()) {
router.onActivityStopped(activity);
}
}
@@ -216,9 +305,11 @@ public class LifecycleHandler extends Fragment implements ActivityLifecycleCallb
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (mActivity == activity) {
for (Router router : mRouterMap.values()) {
router.onActivitySaveInstanceState(activity, outState);
if (this.activity == activity) {
for (Router router : routerMap.values()) {
Bundle bundle = new Bundle();
router.saveInstanceState(bundle);
outState.putBundle(KEY_ROUTER_STATE_PREFIX + router.getContainerId(), bundle);
}
}
}
@@ -0,0 +1,5 @@
package com.bluelinelabs.conductor.internal;
public interface RouterRequiringFunc {
void execute();
}
@@ -6,24 +6,24 @@ import android.util.SparseArray;
public class StringSparseArrayParceler implements Parcelable {
private final SparseArray<String> mStringSparseArray;
private final SparseArray<String> stringSparseArray;
public StringSparseArrayParceler(SparseArray<String> stringSparseArray) {
mStringSparseArray = stringSparseArray;
this.stringSparseArray = stringSparseArray;
}
private StringSparseArrayParceler(Parcel in) {
mStringSparseArray = new SparseArray<>();
stringSparseArray = new SparseArray<>();
final int size = in.readInt();
for (int i = 0; i < size; i++) {
mStringSparseArray.put(in.readInt(), in.readString());
stringSparseArray.put(in.readInt(), in.readString());
}
}
public SparseArray<String> getStringSparseArray() {
return mStringSparseArray;
return stringSparseArray;
}
public int describeContents() {
@@ -31,15 +31,15 @@ public class StringSparseArrayParceler implements Parcelable {
}
public void writeToParcel(Parcel out, int flags) {
final int size = mStringSparseArray.size();
final int size = stringSparseArray.size();
out.writeInt(size);
for (int i = 0; i < size; i++) {
int key = mStringSparseArray.keyAt(i);
int key = stringSparseArray.keyAt(i);
out.writeInt(key);
out.writeString(mStringSparseArray.get(key));
out.writeString(stringSparseArray.get(key));
}
}
@@ -0,0 +1,72 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.IdRes;
import org.robolectric.Robolectric;
import org.robolectric.util.ActivityController;
public class ActivityProxy {
private ActivityController<TestActivity> activityController;
private AttachFakingFrameLayout view;
public ActivityProxy() {
activityController = Robolectric.buildActivity(TestActivity.class);
@IdRes int containerId = 4;
view = new AttachFakingFrameLayout(activityController.get());
view.setId(containerId);
}
public ActivityProxy create(Bundle savedInstanceState) {
activityController.create(savedInstanceState);
return this;
}
public ActivityProxy start() {
activityController.start();
view.setAttached(true);
return this;
}
public ActivityProxy resume() {
activityController.resume();
return this;
}
public ActivityProxy pause() {
activityController.pause();
return this;
}
public ActivityProxy saveInstanceState(Bundle outState) {
activityController.saveInstanceState(outState);
return this;
}
public ActivityProxy stop() {
activityController.stop();
view.setAttached(false);
return this;
}
public ActivityProxy destroy() {
activityController.destroy();
return this;
}
public ActivityProxy rotate() {
getActivity().isChangingConfigurations = true;
getActivity().recreate();
return this;
}
public TestActivity getActivity() {
return activityController.get();
}
public AttachFakingFrameLayout getView() {
return view;
}
}
@@ -0,0 +1,113 @@
package com.bluelinelabs.conductor;
import android.content.Context;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import java.io.FileDescriptor;
public class AttachFakingFrameLayout extends FrameLayout {
final IBinder fakeWindowToken = new IBinder() {
@Override
public String getInterfaceDescriptor() throws RemoteException {
return null;
}
@Override
public boolean pingBinder() {
return false;
}
@Override
public boolean isBinderAlive() {
return false;
}
@Override
public IInterface queryLocalInterface(String descriptor) {
return null;
}
@Override
public void dump(FileDescriptor fd, String[] args) throws RemoteException {
}
@Override
public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException {
}
@Override
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
return false;
}
@Override
public void linkToDeath(DeathRecipient recipient, int flags) throws RemoteException {
}
@Override
public boolean unlinkToDeath(DeathRecipient recipient, int flags) {
return false;
}
};
private boolean reportAttached;
public AttachFakingFrameLayout(Context context) {
super(context);
}
public AttachFakingFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AttachFakingFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public final IBinder getWindowToken() {
return reportAttached ? fakeWindowToken : null;
}
public void setAttached(boolean attached) {
setAttached(attached, true);
}
public void setAttached(boolean attached, boolean reportToViewUtils) {
if (reportAttached != attached) {
reportAttached = attached;
if (reportToViewUtils) {
ViewUtils.reportAttached(this, attached);
}
for (int i = 0; i < getChildCount(); i++) {
ViewUtils.reportAttached(getChildAt(i), attached);
}
}
}
@Override
public void onViewAdded(View child) {
if (reportAttached) {
ViewUtils.reportAttached(child, true);
}
super.onViewAdded(child);
}
@Override
public void onViewRemoved(View child) {
ViewUtils.reportAttached(child, false);
super.onViewRemoved(child);
}
}
@@ -6,61 +6,61 @@ import org.junit.Test;
public class BackstackTests {
private Backstack mBackstack;
private Backstack backstack;
@Before
public void setup() {
mBackstack = new Backstack();
backstack = new Backstack();
}
@Test
public void testPush() {
Assert.assertEquals(0, mBackstack.size());
mBackstack.push(RouterTransaction.builder(new TestController()).build());
Assert.assertEquals(1, mBackstack.size());
Assert.assertEquals(0, backstack.size());
backstack.push(RouterTransaction.with(new TestController()));
Assert.assertEquals(1, backstack.size());
}
@Test
public void testPop() {
mBackstack.push(RouterTransaction.builder(new TestController()).build());
mBackstack.push(RouterTransaction.builder(new TestController()).build());
Assert.assertEquals(2, mBackstack.size());
mBackstack.pop();
Assert.assertEquals(1, mBackstack.size());
mBackstack.pop();
Assert.assertEquals(0, mBackstack.size());
backstack.push(RouterTransaction.with(new TestController()));
backstack.push(RouterTransaction.with(new TestController()));
Assert.assertEquals(2, backstack.size());
backstack.pop();
Assert.assertEquals(1, backstack.size());
backstack.pop();
Assert.assertEquals(0, backstack.size());
}
@Test
public void testPeek() {
RouterTransaction transaction1 = RouterTransaction.builder(new TestController()).build();
RouterTransaction transaction2 = RouterTransaction.builder(new TestController()).build();
RouterTransaction transaction1 = RouterTransaction.with(new TestController());
RouterTransaction transaction2 = RouterTransaction.with(new TestController());
mBackstack.push(transaction1);
Assert.assertEquals(transaction1, mBackstack.peek());
backstack.push(transaction1);
Assert.assertEquals(transaction1, backstack.peek());
mBackstack.push(transaction2);
Assert.assertEquals(transaction2, mBackstack.peek());
backstack.push(transaction2);
Assert.assertEquals(transaction2, backstack.peek());
mBackstack.pop();
Assert.assertEquals(transaction1, mBackstack.peek());
backstack.pop();
Assert.assertEquals(transaction1, backstack.peek());
}
@Test
public void testPopTo() {
RouterTransaction transaction1 = RouterTransaction.builder(new TestController()).build();
RouterTransaction transaction2 = RouterTransaction.builder(new TestController()).build();
RouterTransaction transaction3 = RouterTransaction.builder(new TestController()).build();
RouterTransaction transaction1 = RouterTransaction.with(new TestController());
RouterTransaction transaction2 = RouterTransaction.with(new TestController());
RouterTransaction transaction3 = RouterTransaction.with(new TestController());
mBackstack.push(transaction1);
mBackstack.push(transaction2);
mBackstack.push(transaction3);
backstack.push(transaction1);
backstack.push(transaction2);
backstack.push(transaction3);
Assert.assertEquals(3, mBackstack.size());
Assert.assertEquals(3, backstack.size());
mBackstack.popTo(transaction1);
backstack.popTo(transaction1);
Assert.assertEquals(1, mBackstack.size());
Assert.assertEquals(transaction1, mBackstack.peek());
Assert.assertEquals(1, backstack.size());
Assert.assertEquals(transaction1, backstack.peek());
}
}
@@ -0,0 +1,175 @@
package com.bluelinelabs.conductor;
import android.os.Parcel;
import android.os.Parcelable;
public class CallState implements Parcelable {
public int changeStartCalls;
public int changeEndCalls;
public int createViewCalls;
public int attachCalls;
public int destroyViewCalls;
public int detachCalls;
public int destroyCalls;
public int saveInstanceStateCalls;
public int restoreInstanceStateCalls;
public int saveViewStateCalls;
public int restoreViewStateCalls;
public int onActivityResultCalls;
public int onRequestPermissionsResultCalls;
public int createOptionsMenuCalls;
public CallState() {
this(false);
}
public CallState(boolean setupForAddedController) {
if (setupForAddedController) {
changeStartCalls++;
changeEndCalls++;
createViewCalls++;
attachCalls++;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CallState callState = (CallState)o;
if (changeStartCalls != callState.changeStartCalls) {
return false;
}
if (changeEndCalls != callState.changeEndCalls) {
return false;
}
if (createViewCalls != callState.createViewCalls) {
return false;
}
if (attachCalls != callState.attachCalls) {
return false;
}
if (destroyViewCalls != callState.destroyViewCalls) {
return false;
}
if (detachCalls != callState.detachCalls) {
return false;
}
if (destroyCalls != callState.destroyCalls) {
return false;
}
if (saveInstanceStateCalls != callState.saveInstanceStateCalls) {
return false;
}
if (saveViewStateCalls != callState.saveViewStateCalls) {
return false;
}
if (restoreViewStateCalls != callState.restoreViewStateCalls) {
return false;
}
if (onActivityResultCalls != callState.onActivityResultCalls) {
return false;
}
if (onRequestPermissionsResultCalls != callState.onRequestPermissionsResultCalls) {
return false;
}
if (createOptionsMenuCalls != callState.createOptionsMenuCalls) {
return false;
}
return restoreInstanceStateCalls == callState.restoreInstanceStateCalls;
}
@Override
public int hashCode() {
int result = changeStartCalls;
result = 31 * result + changeEndCalls;
result = 31 * result + createViewCalls;
result = 31 * result + attachCalls;
result = 31 * result + destroyViewCalls;
result = 31 * result + detachCalls;
result = 31 * result + destroyCalls;
result = 31 * result + saveInstanceStateCalls;
result = 31 * result + restoreInstanceStateCalls;
result = 31 * result + saveViewStateCalls;
result = 31 * result + restoreViewStateCalls;
result = 31 * result + onActivityResultCalls;
result = 31 * result + onRequestPermissionsResultCalls;
result = 31 * result + createOptionsMenuCalls;
return result;
}
@Override
public String toString() {
return "\nCallState{" +
"\n changeStartCalls=" + changeStartCalls +
"\n changeEndCalls=" + changeEndCalls +
"\n createViewCalls=" + createViewCalls +
"\n attachCalls=" + attachCalls +
"\n destroyViewCalls=" + destroyViewCalls +
"\n detachCalls=" + detachCalls +
"\n destroyCalls=" + destroyCalls +
"\n saveInstanceStateCalls=" + saveInstanceStateCalls +
"\n restoreInstanceStateCalls=" + restoreInstanceStateCalls +
"\n saveViewStateCalls=" + saveViewStateCalls +
"\n restoreViewStateCalls=" + restoreViewStateCalls +
"\n onActivityResultCalls=" + onActivityResultCalls +
"\n onRequestPermissionsResultCalls=" + onRequestPermissionsResultCalls +
"\n createOptionsMenuCalls=" + createOptionsMenuCalls +
"}\n";
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(changeStartCalls);
out.writeInt(changeEndCalls);
out.writeInt(createViewCalls);
out.writeInt(attachCalls);
out.writeInt(destroyViewCalls);
out.writeInt(detachCalls);
out.writeInt(destroyCalls);
out.writeInt(saveInstanceStateCalls);
out.writeInt(restoreInstanceStateCalls);
out.writeInt(saveViewStateCalls);
out.writeInt(restoreViewStateCalls);
out.writeInt(onActivityResultCalls);
out.writeInt(onRequestPermissionsResultCalls);
out.writeInt(createOptionsMenuCalls);
}
public static final Parcelable.Creator<CallState> CREATOR = new Parcelable.Creator<CallState>() {
public CallState createFromParcel(Parcel in) {
CallState state = new CallState();
state.changeStartCalls = in.readInt();
state.changeEndCalls = in.readInt();
state.createViewCalls = in.readInt();
state.attachCalls = in.readInt();
state.destroyViewCalls = in.readInt();
state.detachCalls = in.readInt();
state.destroyCalls = in.readInt();
state.saveInstanceStateCalls = in.readInt();
state.restoreInstanceStateCalls = in.readInt();
state.saveViewStateCalls = in.readInt();
state.restoreViewStateCalls = in.readInt();
state.onActivityResultCalls = in.readInt();
state.onRequestPermissionsResultCalls = in.readInt();
state.createOptionsMenuCalls = in.readInt();
return state;
}
public CallState[] newArray(int size) {
return new CallState[size];
}
};
}
@@ -13,14 +13,13 @@ public class ControllerChangeHandlerTests {
HorizontalChangeHandler horizontalChangeHandler = new HorizontalChangeHandler();
FadeChangeHandler fadeChangeHandler = new FadeChangeHandler(120, false);
RouterTransaction transaction = RouterTransaction.builder(new TestController())
RouterTransaction transaction = RouterTransaction.with(new TestController())
.pushChangeHandler(horizontalChangeHandler)
.popChangeHandler(fadeChangeHandler)
.build();
RouterTransaction restoredTransaction = new RouterTransaction(transaction.toBundle());
.popChangeHandler(fadeChangeHandler);
RouterTransaction restoredTransaction = new RouterTransaction(transaction.saveInstanceState());
ControllerChangeHandler restoredHorizontal = restoredTransaction.getPushControllerChangeHandler();
ControllerChangeHandler restoredFade = restoredTransaction.getPopControllerChangeHandler();
ControllerChangeHandler restoredHorizontal = restoredTransaction.pushChangeHandler();
ControllerChangeHandler restoredFade = restoredTransaction.popChangeHandler();
Assert.assertEquals(horizontalChangeHandler.getClass(), restoredHorizontal.getClass());
Assert.assertEquals(fadeChangeHandler.getClass(), restoredFade.getClass());
@@ -0,0 +1,562 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Controller.LifecycleListener;
import com.bluelinelabs.conductor.MockChangeHandler.ChangeHandlerListener;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ControllerLifecycleTests {
private Router router;
private ActivityProxy activityProxy;
private CallState currentCallState;
public void createActivityController(Bundle savedInstanceState, boolean includeStartAndResume) {
activityProxy = new ActivityProxy().create(savedInstanceState);
if (includeStartAndResume) {
activityProxy.start().resume();
}
router = Conductor.attachRouter(activityProxy.getActivity(), activityProxy.getView(), savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new TestController()));
}
}
@Before
public void setup() {
createActivityController(null, true);
currentCallState = new CallState();
}
@Test
public void testNormalLifecycle() {
TestController controller = new TestController();
attachLifecycleListener(controller);
CallState expectedCallState = new CallState();
assertCalls(expectedCallState, controller);
router.pushController(RouterTransaction.with(controller)
.pushChangeHandler(getPushHandler(expectedCallState, controller))
.popChangeHandler(getPopHandler(expectedCallState, controller)));
assertCalls(expectedCallState, controller);
router.popCurrentController();
Assert.assertNull(controller.getView());
assertCalls(expectedCallState, controller);
}
@Test
public void testLifecycleWithActivityDestroy() {
TestController controller = new TestController();
attachLifecycleListener(controller);
CallState expectedCallState = new CallState();
assertCalls(expectedCallState, controller);
router.pushController(RouterTransaction.with(controller)
.pushChangeHandler(getPushHandler(expectedCallState, controller)));
assertCalls(expectedCallState, controller);
activityProxy.getActivity().isDestroying = true;
activityProxy.pause();
assertCalls(expectedCallState, controller);
activityProxy.stop();
expectedCallState.saveViewStateCalls++;
expectedCallState.detachCalls++;
expectedCallState.destroyViewCalls++;
assertCalls(expectedCallState, controller);
activityProxy.destroy();
expectedCallState.destroyCalls++;
assertCalls(expectedCallState, controller);
}
@Test
public void testLifecycleWithActivityConfigurationChange() {
TestController controller = new TestController();
attachLifecycleListener(controller);
CallState expectedCallState = new CallState();
assertCalls(expectedCallState, controller);
router.pushController(RouterTransaction.with(controller)
.pushChangeHandler(getPushHandler(expectedCallState, controller))
.tag("root"));
assertCalls(expectedCallState, controller);
activityProxy.getActivity().isChangingConfigurations = true;
Bundle bundle = new Bundle();
activityProxy.saveInstanceState(bundle);
expectedCallState.saveViewStateCalls++;
expectedCallState.saveInstanceStateCalls++;
assertCalls(expectedCallState, controller);
activityProxy.pause();
assertCalls(expectedCallState, controller);
activityProxy.stop();
expectedCallState.detachCalls++;
expectedCallState.destroyViewCalls++;
assertCalls(expectedCallState, controller);
activityProxy.destroy();
assertCalls(expectedCallState, controller);
createActivityController(bundle, false);
controller = (TestController)router.getControllerWithTag("root");
expectedCallState.restoreInstanceStateCalls++;
expectedCallState.restoreViewStateCalls++;
expectedCallState.changeStartCalls++;
expectedCallState.createViewCalls++;
// Lifecycle listener isn't attached during restore, grab the current views from the controller for this stuff...
currentCallState.restoreInstanceStateCalls = controller.currentCallState.restoreInstanceStateCalls;
currentCallState.restoreViewStateCalls = controller.currentCallState.restoreViewStateCalls;
currentCallState.changeStartCalls = controller.currentCallState.changeStartCalls;
currentCallState.changeEndCalls = controller.currentCallState.changeEndCalls;
currentCallState.createViewCalls = controller.currentCallState.createViewCalls;
currentCallState.attachCalls = controller.currentCallState.attachCalls;
assertCalls(expectedCallState, controller);
activityProxy.start().resume();
currentCallState.changeEndCalls = controller.currentCallState.changeEndCalls;
currentCallState.attachCalls = controller.currentCallState.attachCalls;
expectedCallState.changeEndCalls++;
expectedCallState.attachCalls++;
assertCalls(expectedCallState, controller);
activityProxy.resume();
assertCalls(expectedCallState, controller);
}
@Test
public void testLifecycleWithActivityBackground() {
TestController controller = new TestController();
attachLifecycleListener(controller);
CallState expectedCallState = new CallState();
assertCalls(expectedCallState, controller);
router.pushController(RouterTransaction.with(controller)
.pushChangeHandler(getPushHandler(expectedCallState, controller)));
assertCalls(expectedCallState, controller);
activityProxy.pause();
Bundle bundle = new Bundle();
activityProxy.saveInstanceState(bundle);
expectedCallState.saveInstanceStateCalls++;
expectedCallState.saveViewStateCalls++;
assertCalls(expectedCallState, controller);
activityProxy.resume();
}
@Test
public void testLifecycleCallOrder() {
final TestController testController = new TestController();
final CallState callState = new CallState();
testController.addLifecycleListener(new LifecycleListener() {
@Override
public void preCreateView(@NonNull Controller controller) {
callState.createViewCalls++;
Assert.assertEquals(1, callState.createViewCalls);
Assert.assertEquals(0, testController.currentCallState.createViewCalls);
Assert.assertEquals(0, callState.attachCalls);
Assert.assertEquals(0, testController.currentCallState.attachCalls);
Assert.assertEquals(0, callState.detachCalls);
Assert.assertEquals(0, testController.currentCallState.detachCalls);
Assert.assertEquals(0, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void postCreateView(@NonNull Controller controller, @NonNull View view) {
callState.createViewCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(0, callState.attachCalls);
Assert.assertEquals(0, testController.currentCallState.attachCalls);
Assert.assertEquals(0, callState.detachCalls);
Assert.assertEquals(0, testController.currentCallState.detachCalls);
Assert.assertEquals(0, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void preAttach(@NonNull Controller controller, @NonNull View view) {
callState.attachCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(1, callState.attachCalls);
Assert.assertEquals(0, testController.currentCallState.attachCalls);
Assert.assertEquals(0, callState.detachCalls);
Assert.assertEquals(0, testController.currentCallState.detachCalls);
Assert.assertEquals(0, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void postAttach(@NonNull Controller controller, @NonNull View view) {
callState.attachCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(0, callState.detachCalls);
Assert.assertEquals(0, testController.currentCallState.detachCalls);
Assert.assertEquals(0, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void preDetach(@NonNull Controller controller, @NonNull View view) {
callState.detachCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(1, callState.detachCalls);
Assert.assertEquals(0, testController.currentCallState.detachCalls);
Assert.assertEquals(0, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void postDetach(@NonNull Controller controller, @NonNull View view) {
callState.detachCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(2, callState.detachCalls);
Assert.assertEquals(1, testController.currentCallState.detachCalls);
Assert.assertEquals(0, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void preDestroyView(@NonNull Controller controller, @NonNull View view) {
callState.destroyViewCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(2, callState.detachCalls);
Assert.assertEquals(1, testController.currentCallState.detachCalls);
Assert.assertEquals(1, callState.destroyViewCalls);
Assert.assertEquals(0, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void postDestroyView(@NonNull Controller controller) {
callState.destroyViewCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(2, callState.detachCalls);
Assert.assertEquals(1, testController.currentCallState.detachCalls);
Assert.assertEquals(2, callState.destroyViewCalls);
Assert.assertEquals(1, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(0, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void preDestroy(@NonNull Controller controller) {
callState.destroyCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(2, callState.detachCalls);
Assert.assertEquals(1, testController.currentCallState.detachCalls);
Assert.assertEquals(2, callState.destroyViewCalls);
Assert.assertEquals(1, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(1, callState.destroyCalls);
Assert.assertEquals(0, testController.currentCallState.destroyCalls);
}
@Override
public void postDestroy(@NonNull Controller controller) {
callState.destroyCalls++;
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(1, testController.currentCallState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(1, testController.currentCallState.attachCalls);
Assert.assertEquals(2, callState.detachCalls);
Assert.assertEquals(1, testController.currentCallState.detachCalls);
Assert.assertEquals(2, callState.destroyViewCalls);
Assert.assertEquals(1, testController.currentCallState.destroyViewCalls);
Assert.assertEquals(2, callState.destroyCalls);
Assert.assertEquals(1, testController.currentCallState.destroyCalls);
}
});
router.pushController(RouterTransaction.with(testController)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
router.popController(testController);
Assert.assertEquals(2, callState.createViewCalls);
Assert.assertEquals(2, callState.attachCalls);
Assert.assertEquals(2, callState.detachCalls);
Assert.assertEquals(2, callState.destroyViewCalls);
Assert.assertEquals(2, callState.destroyCalls);
}
@Test
public void testChildLifecycle() {
Controller parent = new TestController();
router.pushController(RouterTransaction.with(parent)
.pushChangeHandler(new MockChangeHandler()));
TestController child = new TestController();
attachLifecycleListener(child);
CallState expectedCallState = new CallState();
assertCalls(expectedCallState, child);
Router childRouter = parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null);
childRouter
.setRoot(RouterTransaction.with(child)
.pushChangeHandler(getPushHandler(expectedCallState, child))
.popChangeHandler(getPopHandler(expectedCallState, child)));
assertCalls(expectedCallState, child);
parent.removeChildRouter(childRouter);
assertCalls(expectedCallState, child);
}
@Test
public void testChildLifecycle2() {
Controller parent = new TestController();
router.pushController(RouterTransaction.with(parent)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
TestController child = new TestController();
attachLifecycleListener(child);
CallState expectedCallState = new CallState();
assertCalls(expectedCallState, child);
Router childRouter = parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null);
childRouter
.setRoot(RouterTransaction.with(child)
.pushChangeHandler(getPushHandler(expectedCallState, child))
.popChangeHandler(getPopHandler(expectedCallState, child)));
assertCalls(expectedCallState, child);
router.popCurrentController();
assertCalls(expectedCallState, child);
}
private MockChangeHandler getPushHandler(final CallState expectedCallState, final TestController controller) {
return new MockChangeHandler(new ChangeHandlerListener() {
@Override
void willStartChange() {
expectedCallState.changeStartCalls++;
expectedCallState.createViewCalls++;
assertCalls(expectedCallState, controller);
}
@Override
void didAttachOrDetach() {
expectedCallState.attachCalls++;
assertCalls(expectedCallState, controller);
}
@Override
void didEndChange() {
expectedCallState.changeEndCalls++;
assertCalls(expectedCallState, controller);
}
});
}
private MockChangeHandler getPopHandler(final CallState expectedCallState, final TestController controller) {
return new MockChangeHandler(new ChangeHandlerListener() {
@Override
void willStartChange() {
expectedCallState.changeStartCalls++;
assertCalls(expectedCallState, controller);
}
@Override
void didAttachOrDetach() {
expectedCallState.destroyViewCalls++;
expectedCallState.detachCalls++;
expectedCallState.destroyCalls++;
assertCalls(expectedCallState, controller);
}
@Override
void didEndChange() {
expectedCallState.changeEndCalls++;
assertCalls(expectedCallState, controller);
}
});
}
private void assertCalls(CallState callState, TestController controller) {
Assert.assertEquals("Expected call counts and controller call counts do not match.", callState, controller.currentCallState);
Assert.assertEquals("Expected call counts and lifecycle call counts do not match.", callState, currentCallState);
}
private void attachLifecycleListener(Controller controller) {
controller.addLifecycleListener(new LifecycleListener() {
@Override
public void onChangeStart(@NonNull Controller controller, @NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
currentCallState.changeStartCalls++;
}
@Override
public void onChangeEnd(@NonNull Controller controller, @NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
currentCallState.changeEndCalls++;
}
@Override
public void postCreateView(@NonNull Controller controller, @NonNull View view) {
currentCallState.createViewCalls++;
}
@Override
public void postAttach(@NonNull Controller controller, @NonNull View view) {
currentCallState.attachCalls++;
}
@Override
public void postDestroyView(@NonNull Controller controller) {
currentCallState.destroyViewCalls++;
}
@Override
public void postDetach(@NonNull Controller controller, @NonNull View view) {
currentCallState.detachCalls++;
}
@Override
public void postDestroy(@NonNull Controller controller) {
currentCallState.destroyCalls++;
}
@Override
public void onSaveInstanceState(@NonNull Controller controller, @NonNull Bundle outState) {
currentCallState.saveInstanceStateCalls++;
}
@Override
public void onRestoreInstanceState(@NonNull Controller controller, @NonNull Bundle savedInstanceState) {
currentCallState.restoreInstanceStateCalls++;
}
@Override
public void onSaveViewState(@NonNull Controller controller, @NonNull Bundle outState) {
currentCallState.saveViewStateCalls++;
}
@Override
public void onRestoreViewState(@NonNull Controller controller, @NonNull Bundle savedViewState) {
currentCallState.restoreViewStateCalls++;
}
});
}
}
@@ -1,175 +1,38 @@
package com.bluelinelabs.conductor;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.bluelinelabs.conductor.Controller.LifecycleListener;
import com.bluelinelabs.conductor.Controller.RetainViewMode;
import com.bluelinelabs.conductor.ControllerChangeHandler.ControllerChangeCompletedListener;
import com.bluelinelabs.conductor.ControllerTransaction.ControllerChangeType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ControllerTests {
private ActivityController<TestActivity> mActivityController;
private Router mRouter;
private ActivityProxy activityProxy;
private Router router;
private int mChangeStartCalls;
private int mChangeEndCalls;
private int mBindViewCalls;
private int mAttachCalls;
private int mUnbindViewCalls;
private int mDetachCalls;
private int mDestroyCalls;
public void createActivityController(Bundle savedInstanceState) {
activityProxy = new ActivityProxy().create(savedInstanceState).start().resume();
router = Conductor.attachRouter(activityProxy.getActivity(), activityProxy.getView(), savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new TestController()));
}
}
@Before
public void setup() {
mActivityController = Robolectric.buildActivity(TestActivity.class).create();
Activity activity = mActivityController.get();
mRouter = Conductor.attachRouter(activity, new FrameLayout(activity), null);
mRouter.setRoot(new TestController());
mChangeStartCalls = 0;
mChangeEndCalls = 0;
mBindViewCalls = 0;
mAttachCalls = 0;
mUnbindViewCalls = 0;
mDestroyCalls = 0;
mDestroyCalls = 0;
}
@Test
public void testNormalLifecycle() {
Controller controller = new TestController();
attachLifecycleListener(controller);
assertCalls(0, 0, 0, 0, 0, 0, 0);
mRouter.pushController(RouterTransaction.builder(controller)
.pushChangeHandler(getPushHandler(0, 0, 0, 0, 0, 0, 0))
.popChangeHandler(getPopHandler(1, 1, 1, 1, 0, 0, 0))
.build()
);
assertCalls(1, 1, 1, 1, 0, 0, 0);
mRouter.popCurrentController();
Assert.assertNull(controller.getView());
assertCalls(2, 2, 1, 1, 1, 1, 1);
}
@Test
public void testLifecycleWithActivityDestroy() {
Controller controller = new TestController();
attachLifecycleListener(controller);
assertCalls(0, 0, 0, 0, 0, 0, 0);
mRouter.pushController(RouterTransaction.builder(controller)
.pushChangeHandler(getPushHandler(0, 0, 0, 0, 0, 0, 0))
.build()
);
assertCalls(1, 1, 1, 1, 0, 0, 0);
mActivityController.pause();
assertCalls(1, 1, 1, 1, 0, 0, 0);
mActivityController.stop();
assertCalls(1, 1, 1, 1, 0, 0, 0);
mActivityController.destroy();
ViewUtils.setAttached(controller.getView(), false);
assertCalls(1, 1, 1, 1, 1, 1, 1);
}
@Test
public void testChildLifecycle() {
Controller parent = new TestController();
mRouter.pushController(RouterTransaction.builder(parent)
.pushChangeHandler(new ChangeHandler(new ChangeHandlerListener() {
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
container.addView(to);
ViewUtils.setAttached(to, true);
changeListener.onChangeCompleted();
}
}))
.build());
Controller child = new TestController();
attachLifecycleListener(child);
assertCalls(0, 0, 0, 0, 0, 0, 0);
parent.addChildController(ChildControllerTransaction.builder(child, TestController.VIEW_ID)
.pushChangeHandler(getPushHandler(0, 0, 0, 0, 0, 0, 0))
.popChangeHandler(getPopHandler(1, 1, 1, 1, 0, 0, 0))
.build()
);
assertCalls(1, 1, 1, 1, 0, 0, 0);
parent.removeChildController(child);
assertCalls(2, 2, 1, 1, 1, 1, 1);
}
@Test
public void testChildLifecycle2() {
Controller parent = new TestController();
mRouter.pushController(RouterTransaction.builder(parent)
.pushChangeHandler(new ChangeHandler(new ChangeHandlerListener() {
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
container.addView(to);
ViewUtils.setAttached(to, true);
changeListener.onChangeCompleted();
}
}))
.popChangeHandler(new ChangeHandler(new ChangeHandlerListener() {
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
container.removeView(from);
ViewUtils.setAttached(from, false);
changeListener.onChangeCompleted();
}
}))
.build());
Controller child = new TestController();
attachLifecycleListener(child);
assertCalls(0, 0, 0, 0, 0, 0, 0);
parent.addChildController(ChildControllerTransaction.builder(child, TestController.VIEW_ID)
.pushChangeHandler(getPushHandler(0, 0, 0, 0, 0, 0, 0))
.popChangeHandler(getPopHandler(1, 1, 1, 1, 0, 0, 0))
.build()
);
assertCalls(1, 1, 1, 1, 0, 0, 0);
mRouter.popCurrentController();
ViewUtils.setAttached(child.getView(), false);
assertCalls(1, 1, 1, 1, 1, 1, 1);
createActivityController(null);
}
@Test
@@ -179,20 +42,20 @@ public class ControllerTests {
// Test View getting released w/ RELEASE_DETACH
controller.setRetainViewMode(RetainViewMode.RELEASE_DETACH);
Assert.assertNull(controller.getView());
View view = controller.inflate(new FrameLayout(mRouter.getActivity()));
Assert.assertNull(controller.getView());
ViewUtils.setAttached(view, true);
View view = controller.inflate(new AttachFakingFrameLayout(router.getActivity()));
Assert.assertNotNull(controller.getView());
ViewUtils.setAttached(view, false);
ViewUtils.reportAttached(view, true);
Assert.assertNotNull(controller.getView());
ViewUtils.reportAttached(view, false);
Assert.assertNull(controller.getView());
// Test View getting retained w/ RETAIN_DETACH
controller.setRetainViewMode(RetainViewMode.RETAIN_DETACH);
view = controller.inflate(new FrameLayout(mRouter.getActivity()));
Assert.assertNull(controller.getView());
ViewUtils.setAttached(view, true);
view = controller.inflate(new AttachFakingFrameLayout(router.getActivity()));
Assert.assertNotNull(controller.getView());
ViewUtils.setAttached(view, false);
ViewUtils.reportAttached(view, true);
Assert.assertNotNull(controller.getView());
ViewUtils.reportAttached(view, false);
Assert.assertNotNull(controller.getView());
// Ensure re-setting RELEASE_DETACH releases
@@ -200,98 +63,299 @@ public class ControllerTests {
Assert.assertNull(controller.getView());
}
private ChangeHandler getPushHandler(final int changeStart, final int changeEnd, final int bindView, final int attach, final int unbindView, final int detach, final int destroy) {
return new ChangeHandler(new ChangeHandlerListener() {
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
assertCalls(changeStart + 1, changeEnd, bindView + 1, attach, unbindView, detach, destroy);
container.addView(to);
ViewUtils.setAttached(to, true);
assertCalls(changeStart + 1, changeEnd, bindView + 1, attach + 1, unbindView, detach, destroy);
changeListener.onChangeCompleted();
}
});
@Test
public void testActivityResult() {
TestController controller = new TestController();
CallState expectedCallState = new CallState(true);
router.pushController(RouterTransaction.with(controller));
// Ensure that calling onActivityResult w/o requesting a result doesn't do anything
router.onActivityResult(1, Activity.RESULT_OK, null);
assertCalls(expectedCallState, controller);
// Ensure starting an activity for result gets us the result back
controller.startActivityForResult(new Intent("action"), 1);
router.onActivityResult(1, Activity.RESULT_OK, null);
expectedCallState.onActivityResultCalls++;
assertCalls(expectedCallState, controller);
// Ensure requesting a result w/o calling startActivityForResult works
controller.registerForActivityResult(2);
router.onActivityResult(2, Activity.RESULT_OK, null);
expectedCallState.onActivityResultCalls++;
assertCalls(expectedCallState, controller);
}
private ChangeHandler getPopHandler(final int changeStart, final int changeEnd, final int bindView, final int attach, final int unbindView, final int detach, final int destroy) {
return new ChangeHandler(new ChangeHandlerListener() {
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
assertCalls(changeStart + 1, changeEnd, bindView, attach, unbindView, detach, destroy);
container.removeView(from);
ViewUtils.setAttached(from, false);
assertCalls(changeStart + 1, changeEnd, bindView, attach, unbindView + 1, detach + 1, destroy + 1);
changeListener.onChangeCompleted();
}
});
@Test
public void testActivityResultForChild() {
TestController parent = new TestController();
TestController child = new TestController();
router.pushController(RouterTransaction.with(parent));
parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null)
.setRoot(RouterTransaction.with(child));
CallState childExpectedCallState = new CallState(true);
CallState parentExpectedCallState = new CallState(true);
// Ensure that calling onActivityResult w/o requesting a result doesn't do anything
router.onActivityResult(1, Activity.RESULT_OK, null);
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
// Ensure starting an activity for result gets us the result back
child.startActivityForResult(new Intent("action"), 1);
router.onActivityResult(1, Activity.RESULT_OK, null);
childExpectedCallState.onActivityResultCalls++;
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
// Ensure requesting a result w/o calling startActivityForResult works
child.registerForActivityResult(2);
router.onActivityResult(2, Activity.RESULT_OK, null);
childExpectedCallState.onActivityResultCalls++;
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
}
private void assertCalls(int changeStart, int changeEnd, int bindView, int attach, int unbindView, int detach, int destroy) {
Assert.assertEquals(changeStart, mChangeStartCalls);
Assert.assertEquals(changeEnd, mChangeEndCalls);
Assert.assertEquals(bindView, mBindViewCalls);
Assert.assertEquals(attach, mAttachCalls);
Assert.assertEquals(unbindView, mUnbindViewCalls);
Assert.assertEquals(detach, mDetachCalls);
Assert.assertEquals(destroy, mDestroyCalls);
@Test
public void testPermissionResult() {
final String[] requestedPermissions = new String[] {"test"};
TestController controller = new TestController();
CallState expectedCallState = new CallState(true);
router.pushController(RouterTransaction.with(controller));
// Ensure that calling handleRequestedPermission w/o requesting a result doesn't do anything
router.onRequestPermissionsResult("anotherId", 1, requestedPermissions, new int[] {1});
assertCalls(expectedCallState, controller);
// Ensure requesting the permission gets us the result back
try {
controller.requestPermissions(requestedPermissions, 1);
} catch (NoSuchMethodError ignored) { }
router.onRequestPermissionsResult(controller.getInstanceId(), 1, requestedPermissions, new int[] {1});
expectedCallState.onRequestPermissionsResultCalls++;
assertCalls(expectedCallState, controller);
}
private void attachLifecycleListener(Controller controller) {
controller.addLifecycleListener(new LifecycleListener() {
@Override
public void onChangeStart(@NonNull Controller controller, @NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
mChangeStartCalls++;
}
@Test
public void testPermissionResultForChild() {
final String[] requestedPermissions = new String[] {"test"};
@Override
public void onChangeEnd(@NonNull Controller controller, @NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
mChangeEndCalls++;
}
TestController parent = new TestController();
TestController child = new TestController();
@Override
public void postBindView(@NonNull Controller controller, @NonNull View view) {
mBindViewCalls++;
}
router.pushController(RouterTransaction.with(parent));
parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null)
.setRoot(RouterTransaction.with(child));
@Override
public void postAttach(@NonNull Controller controller, @NonNull View view) {
mAttachCalls++;
}
CallState childExpectedCallState = new CallState(true);
CallState parentExpectedCallState = new CallState(true);
@Override
public void postUnbindView(@NonNull Controller controller) {
mUnbindViewCalls++;
}
// Ensure that calling handleRequestedPermission w/o requesting a result doesn't do anything
router.onRequestPermissionsResult("anotherId", 1, requestedPermissions, new int[] {1});
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
@Override
public void postDetach(@NonNull Controller controller, @NonNull View view) {
mDetachCalls++;
}
// Ensure requesting the permission gets us the result back
try {
child.requestPermissions(requestedPermissions, 1);
} catch (NoSuchMethodError ignored) { }
@Override
public void postDestroy(@NonNull Controller controller) {
mDestroyCalls++;
}
});
router.onRequestPermissionsResult(child.getInstanceId(), 1, requestedPermissions, new int[] {1});
childExpectedCallState.onRequestPermissionsResultCalls++;
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
}
interface ChangeHandlerListener {
void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener);
@Test
public void testOptionsMenu() {
TestController controller = new TestController();
CallState expectedCallState = new CallState(true);
router.pushController(RouterTransaction.with(controller));
// Ensure that calling onCreateOptionsMenu w/o declaring that we have one doesn't do anything
router.onCreateOptionsMenu(null, null);
assertCalls(expectedCallState, controller);
// Ensure calling onCreateOptionsMenu with a menu works
controller.setHasOptionsMenu(true);
// Ensure it'll still get called back next time onCreateOptionsMenu is called
router.onCreateOptionsMenu(null, null);
expectedCallState.createOptionsMenuCalls++;
assertCalls(expectedCallState, controller);
// Ensure we stop getting them when we hide it
controller.setOptionsMenuHidden(true);
router.onCreateOptionsMenu(null, null);
assertCalls(expectedCallState, controller);
// Ensure we get the callback them when we un-hide it
controller.setOptionsMenuHidden(false);
router.onCreateOptionsMenu(null, null);
expectedCallState.createOptionsMenuCalls++;
assertCalls(expectedCallState, controller);
// Ensure we don't get the callback when we no longer have a menu
controller.setHasOptionsMenu(false);
router.onCreateOptionsMenu(null, null);
assertCalls(expectedCallState, controller);
}
static class ChangeHandler extends ControllerChangeHandler {
@Test
public void testOptionsMenuForChild() {
TestController parent = new TestController();
TestController child = new TestController();
private ChangeHandlerListener mListener;
router.pushController(RouterTransaction.with(parent));
parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null)
.setRoot(RouterTransaction.with(child));
public ChangeHandler() { }
CallState childExpectedCallState = new CallState(true);
CallState parentExpectedCallState = new CallState(true);
public ChangeHandler(ChangeHandlerListener listener) {
mListener = listener;
}
// Ensure that calling onCreateOptionsMenu w/o declaring that we have one doesn't do anything
router.onCreateOptionsMenu(null, null);
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
mListener.performChange(container, from, to, isPush, changeListener);
}
// Ensure calling onCreateOptionsMenu with a menu works
child.setHasOptionsMenu(true);
// Ensure it'll still get called back next time onCreateOptionsMenu is called
router.onCreateOptionsMenu(null, null);
childExpectedCallState.createOptionsMenuCalls++;
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
// Ensure we stop getting them when we hide it
child.setOptionsMenuHidden(true);
router.onCreateOptionsMenu(null, null);
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
// Ensure we get the callback them when we un-hide it
child.setOptionsMenuHidden(false);
router.onCreateOptionsMenu(null, null);
childExpectedCallState.createOptionsMenuCalls++;
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
// Ensure we don't get the callback when we no longer have a menu
child.setHasOptionsMenu(false);
router.onCreateOptionsMenu(null, null);
assertCalls(childExpectedCallState, child);
assertCalls(parentExpectedCallState, parent);
}
@Test
public void testAddRemoveChildControllers() {
TestController parent = new TestController();
TestController child1 = new TestController();
TestController child2 = new TestController();
router.pushController(RouterTransaction.with(parent));
Assert.assertEquals(0, parent.getChildRouters().size());
Assert.assertNull(child1.getParentController());
Assert.assertNull(child2.getParentController());
Router childRouter = parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null);
childRouter.setPopsLastView(true);
childRouter.setRoot(RouterTransaction.with(child1));
Assert.assertEquals(1, parent.getChildRouters().size());
Assert.assertEquals(childRouter, parent.getChildRouters().get(0));
Assert.assertEquals(1, childRouter.getBackstackSize());
Assert.assertEquals(child1, childRouter.getControllers().get(0));
Assert.assertEquals(parent, child1.getParentController());
Assert.assertNull(child2.getParentController());
childRouter = parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.VIEW_ID), null);
childRouter.pushController(RouterTransaction.with(child2));
Assert.assertEquals(1, parent.getChildRouters().size());
Assert.assertEquals(childRouter, parent.getChildRouters().get(0));
Assert.assertEquals(2, childRouter.getBackstackSize());
Assert.assertEquals(child1, childRouter.getControllers().get(0));
Assert.assertEquals(child2, childRouter.getControllers().get(1));
Assert.assertEquals(parent, child1.getParentController());
Assert.assertEquals(parent, child2.getParentController());
childRouter.popController(child2);
Assert.assertEquals(1, parent.getChildRouters().size());
Assert.assertEquals(childRouter, parent.getChildRouters().get(0));
Assert.assertEquals(1, childRouter.getBackstackSize());
Assert.assertEquals(child1, childRouter.getControllers().get(0));
Assert.assertEquals(parent, child1.getParentController());
Assert.assertNull(child2.getParentController());
childRouter.popController(child1);
Assert.assertEquals(1, parent.getChildRouters().size());
Assert.assertEquals(childRouter, parent.getChildRouters().get(0));
Assert.assertEquals(0, childRouter.getBackstackSize());
Assert.assertNull(child1.getParentController());
Assert.assertNull(child2.getParentController());
}
@Test
public void testAddRemoveChildRouters() {
TestController parent = new TestController();
TestController child1 = new TestController();
TestController child2 = new TestController();
router.pushController(RouterTransaction.with(parent));
Assert.assertEquals(0, parent.getChildRouters().size());
Assert.assertNull(child1.getParentController());
Assert.assertNull(child2.getParentController());
Router childRouter1 = parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.CHILD_VIEW_ID_1), null);
Router childRouter2 = parent.getChildRouter((ViewGroup)parent.getView().findViewById(TestController.CHILD_VIEW_ID_2), null);
childRouter1.setRoot(RouterTransaction.with(child1));
childRouter2.setRoot(RouterTransaction.with(child2));
Assert.assertEquals(2, parent.getChildRouters().size());
Assert.assertEquals(childRouter1, parent.getChildRouters().get(0));
Assert.assertEquals(childRouter2, parent.getChildRouters().get(1));
Assert.assertEquals(1, childRouter1.getBackstackSize());
Assert.assertEquals(1, childRouter2.getBackstackSize());
Assert.assertEquals(child1, childRouter1.getControllers().get(0));
Assert.assertEquals(child2, childRouter2.getControllers().get(0));
Assert.assertEquals(parent, child1.getParentController());
Assert.assertEquals(parent, child2.getParentController());
parent.removeChildRouter(childRouter2);
Assert.assertEquals(1, parent.getChildRouters().size());
Assert.assertEquals(childRouter1, parent.getChildRouters().get(0));
Assert.assertEquals(1, childRouter1.getBackstackSize());
Assert.assertEquals(0, childRouter2.getBackstackSize());
Assert.assertEquals(child1, childRouter1.getControllers().get(0));
Assert.assertEquals(parent, child1.getParentController());
Assert.assertNull(child2.getParentController());
parent.removeChildRouter(childRouter1);
Assert.assertEquals(0, parent.getChildRouters().size());
Assert.assertEquals(0, childRouter1.getBackstackSize());
Assert.assertEquals(0, childRouter2.getBackstackSize());
Assert.assertNull(child1.getParentController());
Assert.assertNull(child2.getParentController());
}
private void assertCalls(CallState callState, TestController controller) {
Assert.assertEquals("Expected call counts and controller call counts do not match.", callState, controller.currentCallState);
}
}
@@ -1,7 +1,6 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.IdRes;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
@@ -14,39 +13,19 @@ public class ControllerTransactionTests {
@Test
public void testRouterSaveRestore() {
RouterTransaction transaction = RouterTransaction.builder(new TestController())
RouterTransaction transaction = RouterTransaction.with(new TestController())
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new VerticalChangeHandler())
.tag("Test Tag")
.build();
.tag("Test Tag");
Bundle bundle = transaction.toBundle();
Bundle bundle = transaction.saveInstanceState();
RouterTransaction restoredTransaction = new RouterTransaction(bundle);
Assert.assertEquals(transaction.getController().getClass(), restoredTransaction.getController().getClass());
Assert.assertEquals(transaction.getPushControllerChangeHandler().getClass(), restoredTransaction.getPushControllerChangeHandler().getClass());
Assert.assertEquals(transaction.getPopControllerChangeHandler().getClass(), restoredTransaction.getPopControllerChangeHandler().getClass());
Assert.assertEquals(transaction.getTag(), restoredTransaction.getTag());
Assert.assertEquals(transaction.controller.getClass(), restoredTransaction.controller.getClass());
Assert.assertEquals(transaction.pushChangeHandler().getClass(), restoredTransaction.pushChangeHandler().getClass());
Assert.assertEquals(transaction.popChangeHandler().getClass(), restoredTransaction.popChangeHandler().getClass());
Assert.assertEquals(transaction.tag(), restoredTransaction.tag());
}
@Test
public void testChildSaveRestore() {
@IdRes int layoutId = 234;
ChildControllerTransaction transaction = ChildControllerTransaction.builder(new TestController(), layoutId)
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new VerticalChangeHandler())
.tag("Test Tag")
.build();
Bundle bundle = transaction.toBundle();
ChildControllerTransaction restoredTransaction = new ChildControllerTransaction(bundle);
Assert.assertEquals(transaction.containerId, restoredTransaction.containerId);
Assert.assertEquals(transaction.getController().getClass(), restoredTransaction.getController().getClass());
Assert.assertEquals(transaction.getPushControllerChangeHandler().getClass(), restoredTransaction.getPushControllerChangeHandler().getClass());
Assert.assertEquals(transaction.getPopControllerChangeHandler().getClass(), restoredTransaction.getPopControllerChangeHandler().getClass());
Assert.assertEquals(transaction.getTag(), restoredTransaction.getTag());
}
}
@@ -0,0 +1,85 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
public class MockChangeHandler extends ControllerChangeHandler {
private static final String KEY_REMOVES_FROM_VIEW_ON_PUSH = "MockChangeHandler.removesFromViewOnPush";
static class ChangeHandlerListener {
void willStartChange() { }
void didAttachOrDetach() { }
void didEndChange() { }
}
final ChangeHandlerListener listener;
boolean removesFromViewOnPush;
public MockChangeHandler() {
this(true, null);
}
public MockChangeHandler(boolean removesViewOnPush) {
this(removesViewOnPush, null);
}
public MockChangeHandler(@NonNull ChangeHandlerListener listener) {
this(true, listener);
}
public MockChangeHandler(boolean removesFromViewOnPush, ChangeHandlerListener listener) {
this.removesFromViewOnPush = removesFromViewOnPush;
if (listener == null) {
this.listener = new ChangeHandlerListener() { };
} else {
this.listener = listener;
}
}
@Override
public void performChange(@NonNull ViewGroup container, View from, View to, boolean isPush, @NonNull ControllerChangeCompletedListener changeListener) {
listener.willStartChange();
if (isPush) {
container.addView(to);
listener.didAttachOrDetach();
if (removesFromViewOnPush && from != null) {
container.removeView(from);
}
} else {
container.removeView(from);
listener.didAttachOrDetach();
if (to != null) {
container.addView(to);
}
}
changeListener.onChangeCompleted();
listener.didEndChange();
}
@Override
public boolean removesFromViewOnPush() {
return removesFromViewOnPush;
}
@Override
public void saveToBundle(@NonNull Bundle bundle) {
super.saveToBundle(bundle);
bundle.putBoolean(KEY_REMOVES_FROM_VIEW_ON_PUSH, removesFromViewOnPush);
}
@Override
public void restoreFromBundle(@NonNull Bundle bundle) {
super.restoreFromBundle(bundle);
removesFromViewOnPush = bundle.getBoolean(KEY_REMOVES_FROM_VIEW_ON_PUSH);
}
}
@@ -0,0 +1,234 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.view.ViewGroup;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ReattachCaseTests {
private ActivityProxy activityProxy;
private Router router;
public void createActivityController(Bundle savedInstanceState) {
activityProxy = new ActivityProxy().create(savedInstanceState).start().resume();
router = Conductor.attachRouter(activityProxy.getActivity(), activityProxy.getView(), savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new TestController()));
}
}
@Before
public void setup() {
createActivityController(null);
}
@Test
public void testNeedsAttachingOnPauseAndOrientation() {
final TestController controllerA = new TestController();
final TestController controllerB = new TestController();
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertTrue(controllerA.isAttached());
Assert.assertFalse(controllerB.isAttached());
sleepWakeDevice();
Assert.assertTrue(controllerA.isAttached());
Assert.assertFalse(controllerB.isAttached());
router.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
activityProxy.rotate();
router.rebindIfNeeded();
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
}
@Test
public void testChildNeedsAttachOnPauseAndOrientation() {
final TestController controllerA = new TestController();
final TestController childController = new TestController();
final TestController controllerB = new TestController();
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Router childRouter = controllerA.getChildRouter((ViewGroup)controllerA.getView().findViewById(TestController.VIEW_ID), null);
childRouter.pushController(RouterTransaction.with(childController)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertTrue(controllerA.isAttached());
Assert.assertTrue(childController.isAttached());
Assert.assertFalse(controllerB.isAttached());
sleepWakeDevice();
Assert.assertTrue(controllerA.isAttached());
Assert.assertTrue(childController.isAttached());
Assert.assertFalse(controllerB.isAttached());
router.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertFalse(controllerA.isAttached());
Assert.assertFalse(childController.isAttached());
Assert.assertTrue(controllerB.isAttached());
activityProxy.rotate();
router.rebindIfNeeded();
Assert.assertFalse(controllerA.isAttached());
Assert.assertFalse(childController.isAttached());
Assert.assertTrue(childController.getNeedsAttach());
Assert.assertTrue(controllerB.isAttached());
}
@Test
public void testChildHandleBackOnOrientation() {
final TestController controllerA = new TestController();
final TestController controllerB = new TestController();
final TestController childController = new TestController();
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertTrue(controllerA.isAttached());
Assert.assertFalse(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
router.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Router childRouter = controllerB.getChildRouter((ViewGroup)controllerB.getView().findViewById(TestController.VIEW_ID), null);
childRouter.setPopsLastView(true);
childRouter.pushController(RouterTransaction.with(childController)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertTrue(childController.isAttached());
activityProxy.rotate();
router.rebindIfNeeded();
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertTrue(childController.isAttached());
router.handleBack();
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
router.handleBack();
Assert.assertTrue(controllerA.isAttached());
Assert.assertFalse(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
}
// Attempt to test https://github.com/bluelinelabs/Conductor/issues/86#issuecomment-231381271
@Test
public void testReusedChildRouterHandleBackOnOrientation() {
TestController controllerA = new TestController();
TestController controllerB = new TestController();
TestController childController = new TestController();
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertTrue(controllerA.isAttached());
Assert.assertFalse(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
router.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Router childRouter = controllerB.getChildRouter((ViewGroup)controllerB.getView().findViewById(TestController.VIEW_ID), null);
childRouter.setPopsLastView(true);
childRouter.pushController(RouterTransaction.with(childController)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertTrue(childController.isAttached());
router.handleBack();
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
childController = new TestController();
childRouter.pushController(RouterTransaction.with(childController)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertTrue(childController.isAttached());
activityProxy.rotate();
router.rebindIfNeeded();
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertTrue(childController.isAttached());
router.handleBack();
childController = new TestController();
childRouter.pushController(RouterTransaction.with(childController)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertTrue(childController.isAttached());
router.handleBack();
Assert.assertFalse(controllerA.isAttached());
Assert.assertTrue(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
router.handleBack();
Assert.assertTrue(controllerA.isAttached());
Assert.assertFalse(controllerB.isAttached());
Assert.assertFalse(childController.isAttached());
}
private void sleepWakeDevice() {
activityProxy.saveInstanceState(new Bundle()).pause();
activityProxy.resume();
}
}
@@ -1,26 +1,25 @@
package com.bluelinelabs.conductor;
import android.app.Activity;
import android.widget.FrameLayout;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class RouterTests {
private Router mRouter;
private Router router;
@Before
public void setup() {
Activity activity = Robolectric.buildActivity(TestActivity.class).create().get();
mRouter = Conductor.attachRouter(activity, new FrameLayout(activity), null);
ActivityProxy activityProxy = new ActivityProxy().create(null).start().resume();
router = Conductor.attachRouter(activityProxy.getActivity(), activityProxy.getView(), null);
}
@Test
@@ -29,13 +28,13 @@ public class RouterTests {
Controller rootController = new TestController();
Assert.assertFalse(mRouter.hasRootController());
Assert.assertFalse(router.hasRootController());
mRouter.setRoot(rootController, rootTag);
router.setRoot(RouterTransaction.with(rootController).tag(rootTag));
Assert.assertTrue(mRouter.hasRootController());
Assert.assertTrue(router.hasRootController());
Assert.assertEquals(rootController, mRouter.getControllerWithTag(rootTag));
Assert.assertEquals(rootController, router.getControllerWithTag(rootTag));
}
@Test
@@ -46,21 +45,21 @@ public class RouterTests {
Controller oldRootController = new TestController();
Controller newRootController = new TestController();
mRouter.setRoot(oldRootController, oldRootTag);
mRouter.setRoot(newRootController, newRootTag);
router.setRoot(RouterTransaction.with(oldRootController).tag(oldRootTag));
router.setRoot(RouterTransaction.with(newRootController).tag(newRootTag));
Assert.assertNull(mRouter.getControllerWithTag(oldRootTag));
Assert.assertEquals(newRootController, mRouter.getControllerWithTag(newRootTag));
Assert.assertNull(router.getControllerWithTag(oldRootTag));
Assert.assertEquals(newRootController, router.getControllerWithTag(newRootTag));
}
@Test
public void testGetByInstanceId() {
Controller controller = new TestController();
mRouter.pushController(RouterTransaction.builder(controller).build());
router.pushController(RouterTransaction.with(controller));
Assert.assertEquals(controller, mRouter.getControllerWithInstanceId(controller.getInstanceId()));
Assert.assertNull(mRouter.getControllerWithInstanceId("fake id"));
Assert.assertEquals(controller, router.getControllerWithInstanceId(controller.getInstanceId()));
Assert.assertNull(router.getControllerWithInstanceId("fake id"));
}
@Test
@@ -71,16 +70,14 @@ public class RouterTests {
Controller controller1 = new TestController();
Controller controller2 = new TestController();
mRouter.pushController(RouterTransaction.builder(controller1)
.tag(controller1Tag)
.build());
router.pushController(RouterTransaction.with(controller1)
.tag(controller1Tag));
mRouter.pushController(RouterTransaction.builder(controller2)
.tag(controller2Tag)
.build());
router.pushController(RouterTransaction.with(controller2)
.tag(controller2Tag));
Assert.assertEquals(controller1, mRouter.getControllerWithTag(controller1Tag));
Assert.assertEquals(controller2, mRouter.getControllerWithTag(controller2Tag));
Assert.assertEquals(controller1, router.getControllerWithTag(controller1Tag));
Assert.assertEquals(controller2, router.getControllerWithTag(controller2Tag));
}
@Test
@@ -91,31 +88,29 @@ public class RouterTests {
Controller controller1 = new TestController();
Controller controller2 = new TestController();
mRouter.pushController(RouterTransaction.builder(controller1)
.tag(controller1Tag)
.build());
router.pushController(RouterTransaction.with(controller1)
.tag(controller1Tag));
Assert.assertEquals(1, mRouter.getBackstackSize());
Assert.assertEquals(1, router.getBackstackSize());
mRouter.pushController(RouterTransaction.builder(controller2)
.tag(controller2Tag)
.build());
router.pushController(RouterTransaction.with(controller2)
.tag(controller2Tag));
Assert.assertEquals(2, mRouter.getBackstackSize());
Assert.assertEquals(2, router.getBackstackSize());
mRouter.popCurrentController();
router.popCurrentController();
Assert.assertEquals(1, mRouter.getBackstackSize());
Assert.assertEquals(1, router.getBackstackSize());
Assert.assertEquals(controller1, mRouter.getControllerWithTag(controller1Tag));
Assert.assertNull(mRouter.getControllerWithTag(controller2Tag));
Assert.assertEquals(controller1, router.getControllerWithTag(controller1Tag));
Assert.assertNull(router.getControllerWithTag(controller2Tag));
mRouter.popCurrentController();
router.popCurrentController();
Assert.assertEquals(0, mRouter.getBackstackSize());
Assert.assertEquals(0, router.getBackstackSize());
Assert.assertNull(mRouter.getControllerWithTag(controller1Tag));
Assert.assertNull(mRouter.getControllerWithTag(controller2Tag));
Assert.assertNull(router.getControllerWithTag(controller1Tag));
Assert.assertNull(router.getControllerWithTag(controller2Tag));
}
@Test
@@ -130,29 +125,25 @@ public class RouterTests {
Controller controller3 = new TestController();
Controller controller4 = new TestController();
mRouter.pushController(RouterTransaction.builder(controller1)
.tag(controller1Tag)
.build());
router.pushController(RouterTransaction.with(controller1)
.tag(controller1Tag));
mRouter.pushController(RouterTransaction.builder(controller2)
.tag(controller2Tag)
.build());
router.pushController(RouterTransaction.with(controller2)
.tag(controller2Tag));
mRouter.pushController(RouterTransaction.builder(controller3)
.tag(controller3Tag)
.build());
router.pushController(RouterTransaction.with(controller3)
.tag(controller3Tag));
mRouter.pushController(RouterTransaction.builder(controller4)
.tag(controller4Tag)
.build());
router.pushController(RouterTransaction.with(controller4)
.tag(controller4Tag));
mRouter.popToTag(controller2Tag);
router.popToTag(controller2Tag);
Assert.assertEquals(2, mRouter.getBackstackSize());
Assert.assertEquals(controller1, mRouter.getControllerWithTag(controller1Tag));
Assert.assertEquals(controller2, mRouter.getControllerWithTag(controller2Tag));
Assert.assertNull(mRouter.getControllerWithTag(controller3Tag));
Assert.assertNull(mRouter.getControllerWithTag(controller4Tag));
Assert.assertEquals(2, router.getBackstackSize());
Assert.assertEquals(controller1, router.getControllerWithTag(controller1Tag));
Assert.assertEquals(controller2, router.getControllerWithTag(controller2Tag));
Assert.assertNull(router.getControllerWithTag(controller3Tag));
Assert.assertNull(router.getControllerWithTag(controller4Tag));
}
@Test
@@ -165,24 +156,166 @@ public class RouterTests {
Controller controller2 = new TestController();
Controller controller3 = new TestController();
mRouter.pushController(RouterTransaction.builder(controller1)
.tag(controller1Tag)
.build());
router.pushController(RouterTransaction.with(controller1)
.tag(controller1Tag));
mRouter.pushController(RouterTransaction.builder(controller2)
.tag(controller2Tag)
.build());
router.pushController(RouterTransaction.with(controller2)
.tag(controller2Tag));
mRouter.pushController(RouterTransaction.builder(controller3)
.tag(controller3Tag)
.build());
router.pushController(RouterTransaction.with(controller3)
.tag(controller3Tag));
mRouter.popController(controller2);
router.popController(controller2);
Assert.assertEquals(2, mRouter.getBackstackSize());
Assert.assertEquals(controller1, mRouter.getControllerWithTag(controller1Tag));
Assert.assertNull(mRouter.getControllerWithTag(controller2Tag));
Assert.assertEquals(controller3, mRouter.getControllerWithTag(controller3Tag));
Assert.assertEquals(2, router.getBackstackSize());
Assert.assertEquals(controller1, router.getControllerWithTag(controller1Tag));
Assert.assertNull(router.getControllerWithTag(controller2Tag));
Assert.assertEquals(controller3, router.getControllerWithTag(controller3Tag));
}
@Test
public void testSetBackstack() {
RouterTransaction rootTransaction = RouterTransaction.with(new TestController());
RouterTransaction middleTransaction = RouterTransaction.with(new TestController());
RouterTransaction topTransaction = RouterTransaction.with(new TestController());
List<RouterTransaction> backstack = new ArrayList<>();
backstack.add(rootTransaction);
backstack.add(middleTransaction);
backstack.add(topTransaction);
router.setBackstack(backstack, null);
Assert.assertEquals(3, router.getBackstackSize());
List<RouterTransaction> fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(middleTransaction, fetchedBackstack.get(1));
Assert.assertEquals(topTransaction, fetchedBackstack.get(2));
}
@Test
public void testNewSetBackstack() {
router.setRoot(RouterTransaction.with(new TestController()));
Assert.assertEquals(1, router.getBackstackSize());
RouterTransaction rootTransaction = RouterTransaction.with(new TestController());
RouterTransaction middleTransaction = RouterTransaction.with(new TestController());
RouterTransaction topTransaction = RouterTransaction.with(new TestController());
List<RouterTransaction> backstack = new ArrayList<>();
backstack.add(rootTransaction);
backstack.add(middleTransaction);
backstack.add(topTransaction);
router.setBackstack(backstack, null);
Assert.assertEquals(3, router.getBackstackSize());
List<RouterTransaction> fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(middleTransaction, fetchedBackstack.get(1));
Assert.assertEquals(topTransaction, fetchedBackstack.get(2));
}
@Test
public void testNewSetBackstackWithNoRemoveViewOnPush() {
RouterTransaction oldRootTransaction = RouterTransaction.with(new TestController());
RouterTransaction oldTopTransaction = RouterTransaction.with(new TestController()).pushChangeHandler(new MockChangeHandler(false));
router.setRoot(oldRootTransaction);
router.pushController(oldTopTransaction);
Assert.assertEquals(2, router.getBackstackSize());
Assert.assertTrue(oldRootTransaction.controller.isAttached());
Assert.assertTrue(oldTopTransaction.controller.isAttached());
RouterTransaction rootTransaction = RouterTransaction.with(new TestController());
RouterTransaction middleTransaction = RouterTransaction.with(new TestController()).pushChangeHandler(new MockChangeHandler(false));
RouterTransaction topTransaction = RouterTransaction.with(new TestController()).pushChangeHandler(new MockChangeHandler(false));
List<RouterTransaction> backstack = new ArrayList<>();
backstack.add(rootTransaction);
backstack.add(middleTransaction);
backstack.add(topTransaction);
router.setBackstack(backstack, null);
Assert.assertEquals(3, router.getBackstackSize());
List<RouterTransaction> fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(middleTransaction, fetchedBackstack.get(1));
Assert.assertEquals(topTransaction, fetchedBackstack.get(2));
Assert.assertFalse(oldRootTransaction.controller.isAttached());
Assert.assertFalse(oldTopTransaction.controller.isAttached());
Assert.assertTrue(rootTransaction.controller.isAttached());
Assert.assertTrue(middleTransaction.controller.isAttached());
Assert.assertTrue(topTransaction.controller.isAttached());
}
@Test
public void testReplaceTopController() {
RouterTransaction rootTransaction = RouterTransaction.with(new TestController());
RouterTransaction topTransaction = RouterTransaction.with(new TestController());
List<RouterTransaction> backstack = new ArrayList<>();
backstack.add(rootTransaction);
backstack.add(topTransaction);
router.setBackstack(backstack, null);
Assert.assertEquals(2, router.getBackstackSize());
List<RouterTransaction> fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(topTransaction, fetchedBackstack.get(1));
RouterTransaction newTopTransaction = RouterTransaction.with(new TestController());
router.replaceTopController(newTopTransaction);
Assert.assertEquals(2, router.getBackstackSize());
fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(newTopTransaction, fetchedBackstack.get(1));
}
@Test
public void testReplaceTopControllerWithNoRemoveViewOnPush() {
RouterTransaction rootTransaction = RouterTransaction.with(new TestController());
RouterTransaction topTransaction = RouterTransaction.with(new TestController()).pushChangeHandler(new MockChangeHandler(false));
List<RouterTransaction> backstack = new ArrayList<>();
backstack.add(rootTransaction);
backstack.add(topTransaction);
router.setBackstack(backstack, null);
Assert.assertEquals(2, router.getBackstackSize());
Assert.assertTrue(rootTransaction.controller.isAttached());
Assert.assertTrue(topTransaction.controller.isAttached());
List<RouterTransaction> fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(topTransaction, fetchedBackstack.get(1));
RouterTransaction newTopTransaction = RouterTransaction.with(new TestController()).pushChangeHandler(new MockChangeHandler(false));
router.replaceTopController(newTopTransaction);
newTopTransaction.pushChangeHandler().completeImmediately();
Assert.assertEquals(2, router.getBackstackSize());
fetchedBackstack = router.getBackstack();
Assert.assertEquals(rootTransaction, fetchedBackstack.get(0));
Assert.assertEquals(newTopTransaction, fetchedBackstack.get(1));
Assert.assertTrue(rootTransaction.controller.isAttached());
Assert.assertFalse(topTransaction.controller.isAttached());
Assert.assertTrue(newTopTransaction.controller.isAttached());
}
}
@@ -0,0 +1,100 @@
package com.bluelinelabs.conductor;
import android.os.Bundle;
import android.view.ViewGroup;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class TargetControllerTests {
private Router router;
public void createActivityController(Bundle savedInstanceState) {
ActivityProxy activityProxy = new ActivityProxy().create(savedInstanceState).start().resume();
router = Conductor.attachRouter(activityProxy.getActivity(), activityProxy.getView(), savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new TestController()));
}
}
@Before
public void setup() {
createActivityController(null);
}
@Test
public void testSiblingTarget() {
final TestController controllerA = new TestController();
final TestController controllerB = new TestController();
Assert.assertNull(controllerA.getTargetController());
Assert.assertNull(controllerB.getTargetController());
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
controllerB.setTargetController(controllerA);
router.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertNull(controllerA.getTargetController());
Assert.assertEquals(controllerA, controllerB.getTargetController());
}
@Test
public void testParentChildTarget() {
final TestController controllerA = new TestController();
final TestController controllerB = new TestController();
Assert.assertNull(controllerA.getTargetController());
Assert.assertNull(controllerB.getTargetController());
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
controllerB.setTargetController(controllerA);
Router childRouter = controllerA.getChildRouter((ViewGroup)controllerA.getView().findViewById(TestController.VIEW_ID), null);
childRouter.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertNull(controllerA.getTargetController());
Assert.assertEquals(controllerA, controllerB.getTargetController());
}
@Test
public void testChildParentTarget() {
final TestController controllerA = new TestController();
final TestController controllerB = new TestController();
Assert.assertNull(controllerA.getTargetController());
Assert.assertNull(controllerB.getTargetController());
router.pushController(RouterTransaction.with(controllerA)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
controllerA.setTargetController(controllerB);
Router childRouter = controllerA.getChildRouter((ViewGroup)controllerA.getView().findViewById(TestController.VIEW_ID), null);
childRouter.pushController(RouterTransaction.with(controllerB)
.pushChangeHandler(new MockChangeHandler())
.popChangeHandler(new MockChangeHandler()));
Assert.assertNull(controllerB.getTargetController());
Assert.assertEquals(controllerB, controllerA.getTargetController());
}
}
@@ -3,4 +3,17 @@ package com.bluelinelabs.conductor;
import android.app.Activity;
public class TestActivity extends Activity {
public boolean isChangingConfigurations = false;
public boolean isDestroying = false;
@Override
public boolean isChangingConfigurations() {
return isChangingConfigurations;
}
@Override
public boolean isDestroyed() {
return isDestroying || super.isDestroyed();
}
}
@@ -1,8 +1,12 @@
package com.bluelinelabs.conductor;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
@@ -10,15 +14,120 @@ import android.widget.FrameLayout;
public class TestController extends Controller {
@IdRes public static final int VIEW_ID = 2342;
@IdRes public static final int CHILD_VIEW_ID_1 = 2343;
@IdRes public static final int CHILD_VIEW_ID_2 = 2344;
public TestController() { }
private static final String KEY_CALL_STATE = "TestController.currentCallState";
public CallState currentCallState;
public TestController() {
currentCallState = new CallState();
}
@NonNull
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
View view = new FrameLayout(inflater.getContext());
protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
currentCallState.createViewCalls++;
FrameLayout view = new AttachFakingFrameLayout(inflater.getContext());
view.setId(VIEW_ID);
FrameLayout childContainer1 = new FrameLayout(inflater.getContext());
childContainer1.setId(CHILD_VIEW_ID_1);
view.addView(childContainer1);
FrameLayout childContainer2 = new FrameLayout(inflater.getContext());
childContainer2.setId(CHILD_VIEW_ID_2);
view.addView(childContainer2);
return view;
}
@Override
protected void onChangeStarted(@NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
super.onChangeStarted(changeHandler, changeType);
currentCallState.changeStartCalls++;
}
@Override
protected void onChangeEnded(@NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
super.onChangeEnded(changeHandler, changeType);
currentCallState.changeEndCalls++;
}
@Override
protected void onAttach(@NonNull View view) {
super.onAttach(view);
currentCallState.attachCalls++;
}
@Override
protected void onDetach(@NonNull View view) {
super.onDetach(view);
currentCallState.detachCalls++;
}
@Override
protected void onDestroyView(View view) {
super.onDestroyView(view);
currentCallState.destroyViewCalls++;
}
@Override
protected void onDestroy() {
super.onDestroy();
currentCallState.destroyCalls++;
}
@Override
protected void onSaveViewState(@NonNull View view, @NonNull Bundle outState) {
super.onSaveViewState(view, outState);
currentCallState.saveViewStateCalls++;
}
@Override
protected void onRestoreViewState(@NonNull View view, @NonNull Bundle savedViewState) {
super.onRestoreViewState(view, savedViewState);
currentCallState.restoreViewStateCalls++;
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
currentCallState.saveInstanceStateCalls++;
outState.putParcelable(KEY_CALL_STATE, currentCallState);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentCallState = savedInstanceState.getParcelable(KEY_CALL_STATE);
currentCallState.restoreInstanceStateCalls++;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
currentCallState.onActivityResultCalls++;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
currentCallState.onRequestPermissionsResultCalls++;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
currentCallState.createOptionsMenuCalls++;
}
}
@@ -9,9 +9,26 @@ import java.util.List;
public class ViewUtils {
static void setAttached(View view, boolean attached) {
Object listenerInfo = ReflectionHelpers.callInstanceMethod(view, "getListenerInfo");
List<OnAttachStateChangeListener> listeners = ReflectionHelpers.getField(listenerInfo, "mOnAttachStateChangeListeners");
public static void reportAttached(View view, boolean attached) {
if (view instanceof AttachFakingFrameLayout) {
((AttachFakingFrameLayout)view).setAttached(attached, false);
}
List<OnAttachStateChangeListener> listeners = getAttachStateListeners(view);
// Add, then remove an OnAttachStateChangeListener to initialize the attachStateListeners variable inside a view
if (listeners == null) {
OnAttachStateChangeListener tmpListener = new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) { }
@Override
public void onViewDetachedFromWindow(View v) { }
};
view.addOnAttachStateChangeListener(tmpListener);
view.removeOnAttachStateChangeListener(tmpListener);
listeners = getAttachStateListeners(view);
}
for (OnAttachStateChangeListener listener : listeners) {
if (attached) {
@@ -20,6 +37,12 @@ public class ViewUtils {
listener.onViewDetachedFromWindow(view);
}
}
}
private static List<OnAttachStateChangeListener> getAttachStateListeners(View view) {
Object listenerInfo = ReflectionHelpers.callInstanceMethod(view, "getListenerInfo");
return ReflectionHelpers.getField(listenerInfo, "mOnAttachStateChangeListeners");
}
}
+8 -3
View File
@@ -14,6 +14,10 @@ android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
@@ -39,11 +43,12 @@ dependencies {
compile rootProject.ext.supportV4
compile rootProject.ext.supportDesign
apt rootProject.ext.butterknifeCompiler
compile rootProject.ext.butterknife
compile rootProject.ext.picasso
compile 'com.bluelinelabs:conductor:' + rootProject.ext.publishedVersionName
compile 'com.bluelinelabs:conductor-support:' + rootProject.ext.publishedVersionName
compile 'com.bluelinelabs:conductor-rxlifecycle:' + rootProject.ext.publishedVersionName
compile project(':conductor-support')
compile project(':conductor-rxlifecycle')
debugCompile rootProject.ext.leakCanary
releaseCompile rootProject.ext.leakCanaryNoOp
+5 -2
View File
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:tools="http://schemas.android.com/tools"
package="com.bluelinelabs.conductor.demo"
xmlns:android="http://schemas.android.com/apk/res/android">
@@ -7,11 +8,13 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:name="com.bluelinelabs.conductor.demo.App"
android:name="com.bluelinelabs.conductor.demo.DemoApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
android:fullBackupContent="true"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="com.bluelinelabs.conductor.demo.MainActivity"
@@ -0,0 +1,7 @@
package com.bluelinelabs.conductor.demo;
import android.support.v7.app.ActionBar;
public interface ActionBarProvider {
ActionBar getSupportActionBar();
}
@@ -5,7 +5,7 @@ import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
public class App extends Application {
public class DemoApplication extends Application {
public static RefWatcher refWatcher;
@@ -1,21 +1,24 @@
package com.bluelinelabs.conductor.demo;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Conductor;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.demo.controllers.HomeController;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends Activity {
public final class MainActivity extends AppCompatActivity implements ActionBarProvider {
@Bind(R.id.controller_container) ViewGroup mContainer;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.controller_container) ViewGroup container;
private Router mRouter;
private Router router;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -24,23 +27,19 @@ public class MainActivity extends Activity {
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mRouter = Conductor.attachRouter(this, mContainer, savedInstanceState);
if (!mRouter.hasRootController()) {
mRouter.setRoot(new HomeController());
setSupportActionBar(toolbar);
router = Conductor.attachRouter(this, container, savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new HomeController()));
}
}
@Override
public void onBackPressed() {
if (!mRouter.handleBack()) {
if (!router.handleBack()) {
super.onBackPressed();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
}
}
@@ -1,4 +1,4 @@
package com.bluelinelabs.conductor.changehandler;
package com.bluelinelabs.conductor.demo.changehandler;
import android.animation.Animator;
import android.annotation.TargetApi;
@@ -9,6 +9,8 @@ import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.changehandler.AnimatorChangeHandler;
/**
* An {@link AnimatorChangeHandler} that will perform a circular reveal
*/
@@ -18,8 +20,8 @@ public class CircularRevealChangeHandler extends AnimatorChangeHandler {
private static final String KEY_CX = "CircularRevealChangeHandler.cx";
private static final String KEY_CY = "CircularRevealChangeHandler.cy";
private int mCx;
private int mCy;
private int cx;
private int cy;
public CircularRevealChangeHandler() { }
@@ -71,8 +73,8 @@ public class CircularRevealChangeHandler extends AnimatorChangeHandler {
int relativeLeft = fromLocation[0] - containerLocation[0];
int relativeTop = fromLocation[1] - containerLocation[1];
mCx = fromView.getWidth() / 2 + relativeLeft;
mCy = fromView.getHeight() / 2 + relativeTop;
cx = fromView.getWidth() / 2 + relativeLeft;
cy = fromView.getHeight() / 2 + relativeTop;
}
/**
@@ -114,18 +116,18 @@ public class CircularRevealChangeHandler extends AnimatorChangeHandler {
*/
public CircularRevealChangeHandler(int cx, int cy, long duration, boolean removesFromViewOnPush) {
super(duration, removesFromViewOnPush);
mCx = cx;
mCy = cy;
this.cx = cx;
this.cy = cy;
}
@Override
protected Animator getAnimator(@NonNull ViewGroup container, View from, View to, boolean isPush, boolean toAddedToContainer) {
final float radius = (float) Math.hypot(mCx, mCy);
final float radius = (float) Math.hypot(cx, cy);
Animator animator = null;
if (isPush && to != null) {
animator = ViewAnimationUtils.createCircularReveal(to, mCx, mCy, 0, radius);
animator = ViewAnimationUtils.createCircularReveal(to, cx, cy, 0, radius);
} else if (!isPush && from != null) {
animator = ViewAnimationUtils.createCircularReveal(from, mCx, mCy, radius, 0);
animator = ViewAnimationUtils.createCircularReveal(from, cx, cy, radius, 0);
}
return animator;
}
@@ -136,14 +138,14 @@ public class CircularRevealChangeHandler extends AnimatorChangeHandler {
@Override
public void saveToBundle(@NonNull Bundle bundle) {
super.saveToBundle(bundle);
bundle.putInt(KEY_CX, mCx);
bundle.putInt(KEY_CY, mCy);
bundle.putInt(KEY_CX, cx);
bundle.putInt(KEY_CY, cy);
}
@Override
public void restoreFromBundle(@NonNull Bundle bundle) {
super.restoreFromBundle(bundle);
mCx = bundle.getInt(KEY_CX);
mCy = bundle.getInt(KEY_CY);
cx = bundle.getInt(KEY_CX);
cy = bundle.getInt(KEY_CY);
}
}
@@ -0,0 +1,36 @@
package com.bluelinelabs.conductor.demo.changehandler;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
public class CircularRevealChangeHandlerCompat extends CircularRevealChangeHandler {
public CircularRevealChangeHandlerCompat() { }
public CircularRevealChangeHandlerCompat(@NonNull View fromView, @NonNull View containerView) {
super(fromView, containerView);
}
@Override
protected Animator getAnimator(@NonNull ViewGroup container, View from, View to, boolean isPush, boolean toAddedToContainer) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return super.getAnimator(container, from, to, isPush, toAddedToContainer);
} else {
AnimatorSet animator = new AnimatorSet();
if (to != null && toAddedToContainer) {
animator.play(ObjectAnimator.ofFloat(to, View.ALPHA, 0, 1));
}
if (from != null) {
animator.play(ObjectAnimator.ofFloat(from, View.ALPHA, 0));
}
return animator;
}
}
}
@@ -32,8 +32,8 @@ public class FlipChangeHandler extends AnimatorChangeHandler {
}
}
private final long mAnimationDuration;
private final FlipDirection mFlipDirection;
private final long animationDuration;
private final FlipDirection flipDirection;
public FlipChangeHandler() {
this(FlipDirection.RIGHT);
@@ -48,8 +48,8 @@ public class FlipChangeHandler extends AnimatorChangeHandler {
}
public FlipChangeHandler(FlipDirection flipDirection, long animationDuration) {
mFlipDirection = flipDirection;
mAnimationDuration = animationDuration;
this.flipDirection = flipDirection;
this.animationDuration = animationDuration;
}
@Override
@@ -59,22 +59,22 @@ public class FlipChangeHandler extends AnimatorChangeHandler {
if (to != null) {
to.setAlpha(0);
ObjectAnimator rotation = ObjectAnimator.ofFloat(to, mFlipDirection.property, mFlipDirection.inStartRotation, 0).setDuration(mAnimationDuration);
ObjectAnimator rotation = ObjectAnimator.ofFloat(to, flipDirection.property, flipDirection.inStartRotation, 0).setDuration(animationDuration);
rotation.setInterpolator(new AccelerateDecelerateInterpolator());
animatorSet.play(rotation);
Animator alpha = ObjectAnimator.ofFloat(to, View.ALPHA, 1).setDuration(mAnimationDuration / 2);
alpha.setStartDelay(mAnimationDuration / 3);
Animator alpha = ObjectAnimator.ofFloat(to, View.ALPHA, 1).setDuration(animationDuration / 2);
alpha.setStartDelay(animationDuration / 3);
animatorSet.play(alpha);
}
if (from != null) {
ObjectAnimator rotation = ObjectAnimator.ofFloat(from, mFlipDirection.property, 0, mFlipDirection.outEndRotation).setDuration(mAnimationDuration);
ObjectAnimator rotation = ObjectAnimator.ofFloat(from, flipDirection.property, 0, flipDirection.outEndRotation).setDuration(animationDuration);
rotation.setInterpolator(new AccelerateDecelerateInterpolator());
animatorSet.play(rotation);
Animator alpha = ObjectAnimator.ofFloat(from, View.ALPHA, 0).setDuration(mAnimationDuration / 2);
alpha.setStartDelay(mAnimationDuration / 3);
Animator alpha = ObjectAnimator.ofFloat(from, View.ALPHA, 0).setDuration(animationDuration / 2);
alpha.setStartDelay(animationDuration / 3);
animatorSet.play(alpha);
}
@@ -85,7 +85,7 @@ public class FlipChangeHandler extends AnimatorChangeHandler {
protected void resetFromView(@NonNull View from) {
from.setAlpha(1);
switch (mFlipDirection) {
switch (flipDirection) {
case LEFT:
case RIGHT:
from.setRotationY(0);
@@ -8,19 +8,19 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bluelinelabs.conductor.demo.BundleBuilder;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.BundleBuilder;
import butterknife.Bind;
import butterknife.BindView;
public class ChildController extends RefWatchingController {
public class ChildController extends BaseController {
private static final String KEY_TITLE = "ChildController.title";
private static final String KEY_BG_COLOR = "ChildController.bgColor";
private static final String KEY_COLOR_IS_RES = "ChildController.colorIsResId";
@Bind(R.id.tv_title) TextView mTvTitle;
@BindView(R.id.tv_title) TextView tvTitle;
public ChildController(String title, int backgroundColor, boolean colorIsResId) {
this(new BundleBuilder(new Bundle())
@@ -41,10 +41,10 @@ public class ChildController extends RefWatchingController {
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
mTvTitle.setText(getArgs().getString(KEY_TITLE));
tvTitle.setText(getArgs().getString(KEY_TITLE));
int bgColor = getArgs().getInt(KEY_BG_COLOR);
if (getArgs().getBoolean(KEY_COLOR_IS_RES)) {
@@ -10,18 +10,18 @@ import android.widget.TextView;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.changehandler.ScaleFadeChangeHandler;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.widget.ElasticDragDismissFrameLayout;
import com.bluelinelabs.conductor.demo.widget.ElasticDragDismissFrameLayout.ElasticDragDismissCallback;
import butterknife.Bind;
import butterknife.BindView;
@TargetApi(VERSION_CODES.LOLLIPOP)
public class DragDismissController extends RefWatchingController {
public class DragDismissController extends BaseController {
@Bind(R.id.tv_lorem_ipsum) TextView mTvLoremIpsum;
@BindView(R.id.tv_lorem_ipsum) TextView tvLoremIpsum;
private final ElasticDragDismissCallback mDragDismissListener = new ElasticDragDismissCallback() {
private final ElasticDragDismissCallback dragDismissListener = new ElasticDragDismissCallback() {
@Override
public void onDragDismissed() {
overridePopHandler(new ScaleFadeChangeHandler());
@@ -36,21 +36,24 @@ public class DragDismissController extends RefWatchingController {
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
protected void onViewBound(@NonNull View view) {
((ElasticDragDismissFrameLayout)view).addListener(dragDismissListener);
((ElasticDragDismissFrameLayout)view).addListener(mDragDismissListener);
mTvLoremIpsum.setText("Lorem ipsum dolor sit amet, volutpat lacus egestas integer vitae, tempus potenti posuere dolore, elit cras ut vulputate pede eros. Pharetra curabitur, cum ultrices nisi nulla, non a est diamlorem in pede. Feugiat vivamus id, leo massa, pede ligula libero wisi, posuere nec interdum risus. Mauris eros. Scelerisque etiam dignissim, sem odio magna posuere libero in. Eget non posuere, rutrum nunc ut, ipsum ornare, vestibulum nisl turpis, urna interdum. Arcu mi velit. Sem dolor amet sed hymenaeos tempor. Cras felis.\n" +
tvLoremIpsum.setText("Lorem ipsum dolor sit amet, volutpat lacus egestas integer vitae, tempus potenti posuere dolore, elit cras ut vulputate pede eros. Pharetra curabitur, cum ultrices nisi nulla, non a est diamlorem in pede. Feugiat vivamus id, leo massa, pede ligula libero wisi, posuere nec interdum risus. Mauris eros. Scelerisque etiam dignissim, sem odio magna posuere libero in. Eget non posuere, rutrum nunc ut, ipsum ornare, vestibulum nisl turpis, urna interdum. Arcu mi velit. Sem dolor amet sed hymenaeos tempor. Cras felis.\n" +
"Tempus risus vehicula, mauris nulla interdum purus sodales suspendisse, morbi ultrices tempus vitae vestibulum porttitor, vel mus enim tellus non massa in, quis nec fermentum scelerisque sem congue dolores. Accumsan lacinia urna eu feugiat, habitasse wisi cras id nonummy sapien, a pede. Turpis ac donec, adipiscing ut faucibus, odio ut morbi, habitant volutpat lacinia. At vitae ipsum, porttitor wisi hendrerit pellentesque sapien, suspendisse pellentesque praesent sit tellus varius. At in ligula neque imperdiet eget, viverra lectus risus est sem feugiat. Diam amet non phasellus, sed enim ante etiam lorem id at, feugiat eu urna, urna posuere. Amet vel, vehicula ac in fermentum id, elit mauris dolor, eget orci in nec non in vestibulum. Tortor risus mattis, massa vel condimentum non ornare, pede nunc curabitur dui, eu dolorum luctus duis pellentesque. Nec in imperdiet ac tortor pulvinar bibendum. Parturient lacus luctus posuere, quis luctus sociis tellus iaculis.\n" +
"Eu nec, nulla ut neque ac suspendisse, ac purus mattis pretium orci orci, penatibus sollicitudin pellentesque massa, felis et molestie natoque justo vitae. Laoreet nunc nulla augue semper, nulla ridiculus elit in quis bibendum ultrices, integer duis. Dolor ut donec ligula vehicula odio, in lacinia mattis ut quos, semper libero nulla, et euismod ut, nec curabitur turpis aliquet mauris sit a. Tellus interdum dignissim felis. Ultrices dignissim ut, enim urna adipiscing, nunc accumsan justo odio fringilla magna penatibus. Amet integer metus sollicitudin tristique libero dolor, augue nulla pellentesque, massa in suspendisse, adipiscing donec neque nunc. Malesuada non, luctus vestibulum, et at taciti orci felis. Aliquam dolor nibh erat in tincidunt in, risus suscipit integer, quis dolor quis quam. Ultrices dictum, dignissim interdum aenean pede ornare pretium, vehicula adipiscing enim nec magna mollis duis. Imperdiet dolor velit phasellus, laoreet sed ridiculus sollicitudin sit viverra metus, integer sit nunc fusce nonummy augue. Maecenas adipiscing porttitor eu risus nunc malesuada, quo vitae blandit amet feugiat nunc. Pede hac duis in.\n" +
"Lorem posuere ridiculus donec, volutpat vehicula erat nunc ut, justo occaecati vivamus aliquam massa, felis etiam, sed feugiat molestie eu. Et leo non dignissim nam. Fringilla pretium suspendisse vitae nascetur massa hymenaeos, lectus ut senectus amet, a enim. Pellentesque integer erat, mauris morbi pellentesque, sodales phasellus turpis purus nulla porta, massa vulputate consectetuer habitasse malesuada pulvinar, vehicula in elit eros interdum ut. Et enim vulputate, aliquam donec ullamcorper et, vel consequat tincidunt. Ipsum quam sed ante quis at, ultrices eget. Rutrum qui et velit possimus in, odio amet ut adipiscing sed nec, a tellus ut, quam molestie. Nisl adipiscing euismod nec, eget facilisis ac sit. Suspendisse elit amet consequat dolor senectus vivamus, at scelerisque erat, odio doloribus velit et felis neque, turpis adipiscing, arcu varius placerat leo.");
}
@Override
protected void onUnbindView(View view) {
super.onUnbindView(view);
protected void onDestroyView(View view) {
super.onDestroyView(view);
((ElasticDragDismissFrameLayout)view).removeListener(mDragDismissListener);
((ElasticDragDismissFrameLayout)view).removeListener(dragDismissListener);
}
@Override
protected String getTitle() {
return "Drag to Dismiss";
}
}
@@ -1,38 +1,51 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.content.Intent;
import android.graphics.PorterDuff.Mode;
import android.net.Uri;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.URLSpan;
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.ImageView;
import android.widget.TextView;
import com.bluelinelabs.conductor.ChildControllerTransaction;
import com.bluelinelabs.conductor.ControllerChangeHandler;
import com.bluelinelabs.conductor.ControllerChangeType;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class HomeController extends RefWatchingController {
public class HomeController extends BaseController {
public enum HomeDemoModel {
NAVIGATION("Navigation Demos", R.color.red_300),
TRANSITIONS("Transition Demos", R.color.blue_grey_300),
OVERLAY("Overlay Controller", R.color.purple_300),
CHILD_CONTROLLERS("Child Controllers", R.color.orange_300),
VIEW_PAGER("ViewPager", R.color.green_300),
TARGET_CONTROLLER("Target Controller", R.color.pink_300),
MULTIPLE_CHILD_ROUTERS("Multiple Child Routers", R.color.deep_orange_300),
MASTER_DETAIL("Master Detail", R.color.grey_300),
DRAG_DISMISS("Drag Dismiss", R.color.lime_300),
RX_LIFECYCLE("Rx Lifecycle", R.color.teal_300);
RX_LIFECYCLE("Rx Lifecycle", R.color.teal_300),
OVERLAY("Overlay Controller", R.color.purple_300);
String title;
@ColorRes int color;
@@ -43,7 +56,12 @@ public class HomeController extends RefWatchingController {
}
}
@Bind(R.id.recycler_view) RecyclerView mRecyclerView;
@BindView(R.id.recycler_view) RecyclerView recyclerView;
@BindView(R.id.overlay_root) ViewGroup overlayRoot;
public HomeController() {
setHasOptionsMenu(true);
}
@NonNull
@Override
@@ -52,96 +70,154 @@ public class HomeController extends RefWatchingController {
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
mRecyclerView.setAdapter(new HomeAdapter(LayoutInflater.from(view.getContext()), HomeDemoModel.values()));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
recyclerView.setAdapter(new HomeAdapter(LayoutInflater.from(view.getContext()), HomeDemoModel.values()));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.home, menu);
}
@Override
protected void onChangeStarted(@NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
setOptionsMenuHidden(!changeType.isEnter);
if (changeType.isEnter) {
setTitle();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.about) {
SpannableString details = new SpannableString("A small, yet full-featured framework that allows building View-based Android applications");
details.setSpan(new AbsoluteSizeSpan(16, true), 0, details.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
final String url = "https://github.com/bluelinelabs/Conductor";
SpannableString link = new SpannableString(url);
link.setSpan(new URLSpan(url) {
@Override
public void onClick(View widget) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
}, 0, link.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
SpannableStringBuilder content = new SpannableStringBuilder();
content.append("Conductor");
content.append("\n\n");
content.append(details);
content.append("\n\n");
content.append(link);
getChildRouter(overlayRoot, null)
.setPopsLastView(true)
.setRoot(RouterTransaction.with(new OverlayController(content))
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler()));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected String getTitle() {
return "Conductor Demos";
}
void onModelRowClick(HomeDemoModel model) {
switch (model) {
case NAVIGATION:
getRouter().pushController(RouterTransaction.builder(new NavigationDemoController(0))
getRouter().pushController(RouterTransaction.with(new NavigationDemoController(0, true))
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.tag(NavigationDemoController.TAG_UP_TRANSACTION)
.build());
);
break;
case TRANSITIONS:
getRouter().pushController(TransitionDemoController.getRouterTransaction(0, this));
break;
case TARGET_CONTROLLER:
getRouter().pushController(RouterTransaction.builder(new TargetDisplayController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.build());
getRouter().pushController(
RouterTransaction.with(new TargetDisplayController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler()));
break;
case VIEW_PAGER:
getRouter().pushController(RouterTransaction.builder(new PagerController())
getRouter().pushController(RouterTransaction.with(new PagerController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.build());
.popChangeHandler(new FadeChangeHandler()));
break;
case CHILD_CONTROLLERS:
getRouter().pushController(RouterTransaction.builder(new ParentController())
getRouter().pushController(RouterTransaction.with(new ParentController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.build());
.popChangeHandler(new FadeChangeHandler()));
break;
case OVERLAY:
addChildController(ChildControllerTransaction.builder(new OverlayController(), R.id.home_root)
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.addToLocalBackstack(true)
.build());
getChildRouter(overlayRoot, null)
.setPopsLastView(true)
.setRoot(RouterTransaction.with(new OverlayController("I'm an overlay!"))
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler()));
break;
case DRAG_DISMISS:
getRouter().pushController(RouterTransaction.builder(new DragDismissController())
getRouter().pushController(RouterTransaction.with(new DragDismissController())
.pushChangeHandler(new FadeChangeHandler(false))
.popChangeHandler(new FadeChangeHandler())
.build());
.popChangeHandler(new FadeChangeHandler()));
break;
case RX_LIFECYCLE:
getRouter().pushController(RouterTransaction.builder(new RxLifecycleController())
getRouter().pushController(RouterTransaction.with(new RxLifecycleController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.build());
.popChangeHandler(new FadeChangeHandler()));
break;
case MULTIPLE_CHILD_ROUTERS:
getRouter().pushController(RouterTransaction.with(new MultipleChildRouterController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler()));
break;
case MASTER_DETAIL:
getRouter().pushController(RouterTransaction.with(new MasterDetailListController())
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler()));
break;
}
}
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
private final LayoutInflater mInflater;
private final HomeDemoModel[] mItems;
private final LayoutInflater inflater;
private final HomeDemoModel[] items;
public HomeAdapter(LayoutInflater inflater, HomeDemoModel[] items) {
mInflater = inflater;
mItems = items;
this.inflater = inflater;
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(mInflater.inflate(R.layout.row_home, parent, false));
return new ViewHolder(inflater.inflate(R.layout.row_home, parent, false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(mItems[position]);
holder.bind(items[position]);
}
@Override
public int getItemCount() {
return mItems.length;
return items.length;
}
class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.tv_title) TextView mTvTitle;
@Bind(R.id.img_dot) ImageView mImgDot;
private HomeDemoModel mModel;
@BindView(R.id.tv_title) TextView tvTitle;
@BindView(R.id.img_dot) ImageView imgDot;
private HomeDemoModel model;
public ViewHolder(View itemView) {
super(itemView);
@@ -149,14 +225,14 @@ public class HomeController extends RefWatchingController {
}
void bind(HomeDemoModel item) {
mModel = item;
mTvTitle.setText(item.title);
mImgDot.getDrawable().setColorFilter(ContextCompat.getColor(getActivity(), item.color), Mode.SRC_ATOP);
model = item;
tvTitle.setText(item.title);
imgDot.getDrawable().setColorFilter(ContextCompat.getColor(getActivity(), item.color), Mode.SRC_ATOP);
}
@OnClick(R.id.row_root)
void onRowClick() {
onModelRowClick(mModel);
onModelRowClick(model);
}
}
@@ -0,0 +1,158 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MasterDetailListController extends BaseController {
private static final String KEY_SELECTED_INDEX = "MasterDetailListController.selectedIndex";
public enum DetailItemModel {
ONE("Item 1", "This is a quick demo of master/detail flow using Conductor. In portrait mode you'll see a standard list. In landscape, you'll see a two-pane layout.", R.color.green_300),
TWO("Item 2", "This is another item.", R.color.cyan_300),
THREE("Item 3", "Wow, a 3rd item!", R.color.deep_purple_300);
String title;
String detail;
int backgroundColor;
DetailItemModel(String title, String detail, int backgroundColor) {
this.title = title;
this.detail = detail;
this.backgroundColor = backgroundColor;
}
}
@BindView(R.id.recycler_view) RecyclerView recyclerView;
@Nullable @BindView(R.id.detail_container) ViewGroup detailContainer;
private int selectedIndex;
private boolean twoPaneView;
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return inflater.inflate(R.layout.controller_master_detail_list, container, false);
}
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
recyclerView.setAdapter(new DetailItemAdapter(LayoutInflater.from(view.getContext()), DetailItemModel.values()));
twoPaneView = (detailContainer != null);
if (twoPaneView) {
onRowSelected(selectedIndex);
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_SELECTED_INDEX, selectedIndex);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
selectedIndex = savedInstanceState.getInt(KEY_SELECTED_INDEX);
}
@Override
protected String getTitle() {
return "Master/Detail Flow";
}
void onRowSelected(int index) {
selectedIndex = index;
DetailItemModel model = DetailItemModel.values()[index];
ChildController controller = new ChildController(model.detail, model.backgroundColor, true);
if (twoPaneView) {
getChildRouter(detailContainer, null).setRoot(RouterTransaction.with(controller));
} else {
getRouter().pushController(RouterTransaction.with(controller)
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler()));
}
}
class DetailItemAdapter extends RecyclerView.Adapter<DetailItemAdapter.ViewHolder> {
private final LayoutInflater inflater;
private final DetailItemModel[] items;
public DetailItemAdapter(LayoutInflater inflater, DetailItemModel[] items) {
this.inflater = inflater;
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(inflater.inflate(R.layout.row_detail_item, parent, false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items[position], position);
}
@Override
public int getItemCount() {
return items.length;
}
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.row_root) View root;
@BindView(R.id.tv_title) TextView tvTitle;
private int position;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
void bind(DetailItemModel item, int position) {
tvTitle.setText(item.title);
this.position = position;
if (twoPaneView && position == selectedIndex) {
root.setBackgroundColor(ContextCompat.getColor(root.getContext(), R.color.grey_400));
} else {
root.setBackgroundColor(ContextCompat.getColor(root.getContext(), android.R.color.transparent));
}
}
@OnClick(R.id.row_root)
void onRowClick() {
onRowSelected(position);
notifyDataSetChanged();
}
}
}
}
@@ -0,0 +1,41 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import butterknife.BindViews;
public class MultipleChildRouterController extends BaseController {
@BindViews({R.id.container_0, R.id.container_1, R.id.container_2}) ViewGroup[] childContainers;
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return inflater.inflate(R.layout.controller_multiple_child_routers, container, false);
}
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
for (ViewGroup childContainer : childContainers) {
Router childRouter = getChildRouter(childContainer, null).setPopsLastView(false);
if (!childRouter.hasRootController()) {
childRouter.setRoot(RouterTransaction.with(new NavigationDemoController(0, false)));
}
}
}
@Override
protected String getTitle() {
return "Child Router Demo";
}
}
@@ -9,33 +9,37 @@ import android.widget.TextView;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.demo.BundleBuilder;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.BundleBuilder;
import com.bluelinelabs.conductor.demo.util.ColorUtil;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.OnClick;
public class NavigationDemoController extends RefWatchingController {
public class NavigationDemoController extends BaseController {
public static final String TAG_UP_TRANSACTION = "NavigationDemoController.up";
private static final String KEY_INDEX = "NavigationDemoController.index";
private static final String KEY_DISPLAY_UP = "NavigationDemoController.displayUp";
@Bind(R.id.tv_title) TextView mTvTitle;
@BindView(R.id.tv_title) TextView tvTitle;
private int mIndex;
private int index;
private boolean displayUp;
public NavigationDemoController(int index) {
public NavigationDemoController(int index, boolean displayUpButton) {
this(new BundleBuilder(new Bundle())
.putInt(KEY_INDEX, index)
.putBoolean(KEY_DISPLAY_UP, displayUpButton)
.build());
}
public NavigationDemoController(Bundle args) {
super(args);
mIndex = args.getInt(KEY_INDEX);
index = args.getInt(KEY_INDEX);
displayUp = args.getBoolean(KEY_DISPLAY_UP);
}
@NonNull
@@ -45,19 +49,26 @@ public class NavigationDemoController extends RefWatchingController {
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
view.setBackgroundColor(ColorUtil.getMaterialColor(getResources(), mIndex));
mTvTitle.setText(getResources().getString(R.string.navigation_title, mIndex));
if (!displayUp) {
view.findViewById(R.id.btn_up).setVisibility(View.GONE);
}
view.setBackgroundColor(ColorUtil.getMaterialColor(getResources(), index));
tvTitle.setText(getResources().getString(R.string.navigation_title, index));
}
@Override
protected String getTitle() {
return "Navigation Demos";
}
@OnClick(R.id.btn_next) void onNextClicked() {
getRouter().pushController(RouterTransaction.builder(new NavigationDemoController(mIndex + 1))
getRouter().pushController(RouterTransaction.with(new NavigationDemoController(index + 1, displayUp))
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())
.build()
);
.popChangeHandler(new HorizontalChangeHandler()));
}
@OnClick(R.id.btn_up) void onUpClicked() {
@@ -1,19 +1,34 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.BundleBuilder;
import butterknife.Bind;
import butterknife.BindView;
public class OverlayController extends RefWatchingController {
public class OverlayController extends BaseController {
@Bind(R.id.text_view) TextView mTextView;
private static final String KEY_TEXT = "OverlayController.text";
@BindView(R.id.text_view) TextView textView;
public OverlayController(CharSequence text) {
this(new BundleBuilder(new Bundle())
.putCharSequence(KEY_TEXT, text)
.build());
}
public OverlayController(Bundle args) {
super(args);
}
@NonNull
@Override
@@ -22,9 +37,10 @@ public class OverlayController extends RefWatchingController {
}
@Override
public void onBindView(@NonNull View view) {
super.onBindView(view);
mTextView.setText("I'm an Overlay");
public void onViewBound(@NonNull View view) {
super.onViewBound(view);
textView.setText(getArgs().getCharSequence(KEY_TEXT));
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
@@ -1,6 +1,7 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
@@ -8,43 +9,50 @@ import android.view.ViewGroup;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.support.ControllerPagerAdapter;
import butterknife.Bind;
import butterknife.BindView;
public class PagerController extends RefWatchingController {
public class PagerController extends BaseController {
@Bind(R.id.view_pager) ViewPager mViewPager;
private ControllerPagerAdapter mPagerAdapter;
private int[] PAGE_COLORS = new int[]{R.color.green_300, R.color.cyan_300, R.color.deep_purple_300, R.color.lime_300, R.color.red_300};
@BindView(R.id.tab_layout) TabLayout tabLayout;
@BindView(R.id.view_pager) ViewPager viewPager;
private final ControllerPagerAdapter pagerAdapter;
public PagerController() {
mPagerAdapter = new ControllerPagerAdapter(this) {
pagerAdapter = new ControllerPagerAdapter(this, false) {
@Override
public Controller getItem(int position) {
switch (position) {
case 0:
return new ChildController("Child #1 (Swipe to see more)", R.color.cyan_300, true);
case 1:
return new ChildController("Child #2 (Swipe to see more)", R.color.deep_purple_300, true);
case 2:
return new ChildController("Child #3 (Swipe to see more)", R.color.lime_300, true);
default:
throw new RuntimeException("Invalid item position: " + position);
}
return new ChildController(String.format("Child #%d (Swipe to see more)", position), PAGE_COLORS[position], true);
}
@Override
public int getCount() {
return 3;
return PAGE_COLORS.length;
}
@Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
};
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
mViewPager.setAdapter(mPagerAdapter);
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
@Override
protected void onDestroyView(View view) {
viewPager.setAdapter(null);
super.onDestroyView(view);
}
@NonNull
@@ -53,4 +61,9 @@ public class PagerController extends RefWatchingController {
return inflater.inflate(R.layout.controller_pager, container, false);
}
@Override
protected String getTitle() {
return "ViewPager Demo";
}
}
@@ -1,25 +1,28 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.ChildControllerTransaction;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.ControllerChangeHandler;
import com.bluelinelabs.conductor.ControllerTransaction.ControllerChangeType;
import com.bluelinelabs.conductor.ControllerChangeType;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.ColorUtil;
import java.util.List;
public class ParentController extends RefWatchingController {
public class ParentController extends BaseController {
private static final int NUMBER_OF_CHILDREN = 5;
private boolean mFinishing;
private boolean finishing;
private boolean hasShownAll;
@NonNull
@Override
@@ -37,41 +40,65 @@ public class ParentController extends RefWatchingController {
}
private void addChild(final int index) {
int frameId = getResources().getIdentifier("child_content_" + (index + 1), "id", getActivity().getPackageName());
@IdRes final int frameId = getResources().getIdentifier("child_content_" + (index + 1), "id", getActivity().getPackageName());
final ViewGroup container = (ViewGroup)getView().findViewById(frameId);
final Router childRouter = getChildRouter(container, null).setPopsLastView(true);
ChildController childController = new ChildController("Child Controller #" + index, ColorUtil.getMaterialColor(getResources(), index), false);
addChildController(ChildControllerTransaction.builder(childController, frameId)
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler())
.build());
if (!childRouter.hasRootController()) {
ChildController childController = new ChildController("Child Controller #" + index, ColorUtil.getMaterialColor(getResources(), index), false);
childController.addLifecycleListener(new LifecycleListener() {
@Override
public void onChangeEnd(@NonNull Controller controller, @NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
if (changeType == ControllerChangeType.PUSH_ENTER && index < NUMBER_OF_CHILDREN - 1) {
addChild(index + 1);
} else if (changeType == ControllerChangeType.POP_EXIT) {
if (index > 0) {
removeChild(index - 1);
} else {
getRouter().popController(ParentController.this);
childController.addLifecycleListener(new LifecycleListener() {
@Override
public void onChangeEnd(@NonNull Controller controller, @NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
if (changeType == ControllerChangeType.PUSH_ENTER && !hasShownAll) {
if (index < NUMBER_OF_CHILDREN - 1) {
addChild(index + 1);
} else {
hasShownAll = true;
}
} else if (changeType == ControllerChangeType.POP_EXIT) {
if (index > 0) {
removeChild(index - 1);
} else {
getRouter().popController(ParentController.this);
}
}
}
}
});
});
childRouter.setRoot(RouterTransaction.with(childController)
.pushChangeHandler(new FadeChangeHandler())
.popChangeHandler(new FadeChangeHandler()));
}
}
private void removeChild(int index) {
List<Controller> childControllers = getChildControllers();
removeChildController(childControllers.get(index));
List<Router> childRouters = getChildRouters();
if (index < childRouters.size()) {
removeChildRouter(childRouters.get(index));
}
}
@Override
public boolean handleBack() {
if (getChildControllers().size() == NUMBER_OF_CHILDREN && !mFinishing) {
mFinishing = true;
removeChild(getChildControllers().size() - 1);
int childControllers = 0;
for (Router childRouter : getChildRouters()) {
if (childRouter.hasRootController()) {
childControllers++;
}
}
if (childControllers != NUMBER_OF_CHILDREN || finishing) {
return true;
} else {
finishing = true;
return super.handleBack();
}
return true;
}
@Override
protected String getTitle() {
return "Parent/Child Demo";
}
}
@@ -10,12 +10,12 @@ import android.widget.TextView;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.rxlifecycle.ControllerEvent;
import java.util.concurrent.TimeUnit;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action0;
@@ -23,11 +23,11 @@ import rx.functions.Action1;
// Shamelessly borrowed from the official RxLifecycle demo by Trello and adapted for Conductor Controllers
// instead of Activities or Fragments.
public class RxLifecycleController extends RefWatchingController {
public class RxLifecycleController extends BaseController {
private static final String TAG = "RxLifecycleController";
@Bind(R.id.tv_title) TextView mTvTitle;
@BindView(R.id.tv_title) TextView tvTitle;
public RxLifecycleController() {
@@ -48,25 +48,23 @@ public class RxLifecycleController extends RefWatchingController {
}
@Override
public void onBindView(@NonNull View view) {
super.onBindView(view);
public void onViewBound(@NonNull View view) {
Log.i(TAG, "onCreateView() called");
Log.i(TAG, "onBindView() called");
mTvTitle.setText(getResources().getString(R.string.rxlifecycle_title, TAG));
tvTitle.setText(getResources().getString(R.string.rxlifecycle_title, TAG));
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
Log.i(TAG, "Unsubscribing from onBindView()");
Log.i(TAG, "Unsubscribing from onCreateView)");
}
})
.compose(this.<Long>bindUntilEvent(ControllerEvent.UNBIND_VIEW))
.compose(this.<Long>bindUntilEvent(ControllerEvent.DESTROY_VIEW))
.subscribe(new Action1<Long>() {
@Override
public void call(Long num) {
Log.i(TAG, "Started in onBindView(), running until onUnbindView(): " + num);
Log.i(TAG, "Started in onCreateView(), running until onDestroyView(): " + num);
}
});
}
@@ -94,10 +92,10 @@ public class RxLifecycleController extends RefWatchingController {
}
@Override
protected void onUnbindView(View view) {
super.onUnbindView(view);
protected void onDestroyView(View view) {
super.onDestroyView(view);
Log.i(TAG, "onUnbindView() called");
Log.i(TAG, "onDestroyView() called");
}
@Override
@@ -114,6 +112,11 @@ public class RxLifecycleController extends RefWatchingController {
Log.i(TAG, "onDestroy() called");
}
@Override
protected String getTitle() {
return "RxLifecycle Demo";
}
@NonNull
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
@@ -123,20 +126,16 @@ public class RxLifecycleController extends RefWatchingController {
@OnClick(R.id.btn_next_release_view) void onNextWithReleaseClicked() {
setRetainViewMode(RetainViewMode.RELEASE_DETACH);
getRouter().pushController(RouterTransaction.builder(new TextController("Logcat should now report that the observables from onAttach() and onBindView() have been unsubscribed from, while the constructor observable is still running."))
getRouter().pushController(RouterTransaction.with(new TextController("Logcat should now report that the observables from onAttach() and onViewBound() have been unsubscribed from, while the constructor observable is still running."))
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())
.build()
);
.popChangeHandler(new HorizontalChangeHandler()));
}
@OnClick(R.id.btn_next_retain_view) void onNextWithRetainClicked() {
setRetainViewMode(RetainViewMode.RETAIN_DETACH);
getRouter().pushController(RouterTransaction.builder(new TextController("Logcat should now report that the observables from onAttach() has been unsubscribed from, while the constructor and onBindView() observables are still running."))
getRouter().pushController(RouterTransaction.with(new TextController("Logcat should now report that the observables from onAttach() has been unsubscribed from, while the constructor and onViewBound() observables are still running."))
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())
.build()
);
.popChangeHandler(new HorizontalChangeHandler()));
}
}
@@ -17,23 +17,24 @@ import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.TargetTitleEntryController.TargetTitleEntryControllerListener;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.squareup.picasso.Picasso;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.OnClick;
public class TargetDisplayController extends RefWatchingController implements TargetTitleEntryControllerListener {
public class TargetDisplayController extends BaseController implements TargetTitleEntryControllerListener {
private static final int REQUEST_SELECT_IMAGE = 126;
private static final String KEY_SELECTED_TEXT = "TargetDisplayController.selectedText";
private static final String KEY_SELECTED_IMAGE = "TargetDisplayController.selectedImage";
@Bind(R.id.tv_selection) TextView mTvSelection;
@Bind(R.id.image_view) ImageView mImageView;
@BindView(R.id.tv_selection) TextView tvSelection;
@BindView(R.id.image_view) ImageView imageView;
private String mSelectedText;
private Uri mImageUri;
private String selectedText;
private Uri imageUri;
@NonNull
@Override
@@ -42,10 +43,9 @@ public class TargetDisplayController extends RefWatchingController implements Ta
}
@OnClick(R.id.btn_pick_title) void launchTitlePicker() {
getRouter().pushController(RouterTransaction.builder(new TargetTitleEntryController(this))
getRouter().pushController(RouterTransaction.with(new TargetTitleEntryController(this))
.pushChangeHandler(new HorizontalChangeHandler())
.popChangeHandler(new HorizontalChangeHandler())
.build());
.popChangeHandler(new HorizontalChangeHandler()));
}
@OnClick(R.id.btn_pick_image) void launchImagePicker() {
@@ -57,21 +57,21 @@ public class TargetDisplayController extends RefWatchingController implements Ta
@Override
public void onTitlePicked(String option) {
mSelectedText = option;
selectedText = option;
setTextView();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_IMAGE && resultCode == Activity.RESULT_OK) {
mImageUri = data.getData();
imageUri = data.getData();
setImageView();
}
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
setTextView();
setImageView();
}
@@ -79,31 +79,40 @@ public class TargetDisplayController extends RefWatchingController implements Ta
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_SELECTED_TEXT, mSelectedText);
outState.putString(KEY_SELECTED_IMAGE, mImageUri != null ? mImageUri.toString() : null);
outState.putString(KEY_SELECTED_TEXT, selectedText);
outState.putString(KEY_SELECTED_IMAGE, imageUri != null ? imageUri.toString() : null);
}
@Override
public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mSelectedText = savedInstanceState.getString(KEY_SELECTED_TEXT);
selectedText = savedInstanceState.getString(KEY_SELECTED_TEXT);
String uriString = savedInstanceState.getString(KEY_SELECTED_IMAGE);
if (!TextUtils.isEmpty(uriString)) {
mImageUri = Uri.parse(uriString);
imageUri = Uri.parse(uriString);
}
}
@Override
protected String getTitle() {
return "Target Controller Demo";
}
private void setImageView() {
mImageView.setImageURI(mImageUri);
Picasso.with(getActivity())
.load(imageUri)
.fit()
.centerCrop()
.into(imageView);
}
private void setTextView() {
if (mTvSelection != null) {
if (!TextUtils.isEmpty(mSelectedText)) {
mTvSelection.setText(mSelectedText);
if (tvSelection != null) {
if (!TextUtils.isEmpty(selectedText)) {
tvSelection.setText(selectedText);
} else {
mTvSelection.setText("Press pick title to set this title, or pick image to fill in the image view.");
tvSelection.setText("Press pick title to set this title, or pick image to fill in the image view.");
}
}
}
@@ -1,30 +1,38 @@
package com.bluelinelabs.conductor.demo.controllers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.OnClick;
public class TargetTitleEntryController extends RefWatchingController {
public class TargetTitleEntryController extends BaseController {
public interface TargetTitleEntryControllerListener {
void onTitlePicked(String option);
}
@Bind(R.id.edit_text) EditText mEditText;
@BindView(R.id.edit_text) EditText editText;
public <T extends Controller & TargetTitleEntryControllerListener> TargetTitleEntryController(T targetController) {
setTargetController(targetController);
}
public TargetTitleEntryController() { }
public TargetTitleEntryController(Controller targetController) {
setTargetController(targetController);
@Override
protected void onDetach(@NonNull View view) {
InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
@NonNull
@@ -34,18 +42,14 @@ public class TargetTitleEntryController extends RefWatchingController {
}
@Override
public void onTargetControllerSet(Controller target) {
super.onTargetControllerSet(target);
if (!(target instanceof TargetTitleEntryControllerListener)) {
throw new RuntimeException(getClass().getSimpleName() + " target Controllers must implement the " + TargetTitleEntryControllerListener.class.getSimpleName() + " interface.");
}
protected String getTitle() {
return "Target Controller Demo";
}
@OnClick(R.id.btn_use_title) void optionPicked() {
Controller targetController = getTargetController();
if (targetController != null) {
((TargetTitleEntryControllerListener)targetController).onTitlePicked(mEditText.getText().toString());
((TargetTitleEntryControllerListener)targetController).onTitlePicked(editText.getText().toString());
getRouter().popController(this);
}
}
@@ -7,17 +7,17 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bluelinelabs.conductor.demo.BundleBuilder;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.BundleBuilder;
import butterknife.Bind;
import butterknife.BindView;
public class TextController extends RefWatchingController {
public class TextController extends BaseController {
private static final String KEY_TEXT = "TextController.text";
@Bind(R.id.text_view) TextView mTextView;
@BindView(R.id.text_view) TextView textView;
public TextController(String text) {
this(new BundleBuilder(new Bundle())
@@ -37,9 +37,9 @@ public class TextController extends RefWatchingController {
}
@Override
public void onBindView(@NonNull View view) {
super.onBindView(view);
mTextView.setText(getArgs().getString(KEY_TEXT));
public void onViewBound(@NonNull View view) {
super.onViewBound(view);
textView.setText(getArgs().getString(KEY_TEXT));
}
}
@@ -15,27 +15,27 @@ import android.widget.TextView;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.ControllerChangeHandler;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.CircularRevealChangeHandler;
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler;
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
import com.bluelinelabs.conductor.demo.BundleBuilder;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.changehandler.ArcFadeMoveChangeHandlerCompat;
import com.bluelinelabs.conductor.demo.changehandler.CircularRevealChangeHandlerCompat;
import com.bluelinelabs.conductor.demo.changehandler.FlipChangeHandler;
import com.bluelinelabs.conductor.demo.controllers.base.RefWatchingController;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.BundleBuilder;
import butterknife.Bind;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class TransitionDemoController extends RefWatchingController {
public class TransitionDemoController extends BaseController {
private static final String KEY_INDEX = "TransitionDemoController.index";
public enum TransitionDemo {
VERTICAL("Vertical Slide Animation", R.layout.controller_transition_demo, R.color.blue_grey_300),
CIRCULAR("Circular Reveal Animation", R.layout.controller_transition_demo, R.color.red_300),
CIRCULAR("Circular Reveal Animation (on Lollipop and above, else Fade)", R.layout.controller_transition_demo, R.color.red_300),
FADE("Fade Animation", R.layout.controller_transition_demo, R.color.blue_300),
FLIP("Flip Animation", R.layout.controller_transition_demo, R.color.deep_orange_300),
HORIZONTAL("Horizontal Slide Animation", R.layout.controller_transition_demo, R.color.green_300),
@@ -56,11 +56,11 @@ public class TransitionDemoController extends RefWatchingController {
}
}
@Bind(R.id.tv_title) TextView mTvTitle;
@Bind(R.id.btn_next) FloatingActionButton mBtnNext;
View mContainerView;
@BindView(R.id.tv_title) TextView tvTitle;
@BindView(R.id.btn_next) FloatingActionButton btnNext;
@BindView(R.id.transition_root) View containerView;
private TransitionDemo mTransitionDemo;
private TransitionDemo transitionDemo;
public TransitionDemoController(int index) {
this(new BundleBuilder(new Bundle())
@@ -70,19 +70,25 @@ public class TransitionDemoController extends RefWatchingController {
public TransitionDemoController(Bundle args) {
super(args);
mTransitionDemo = TransitionDemo.fromIndex(args.getInt(KEY_INDEX));
transitionDemo = TransitionDemo.fromIndex(args.getInt(KEY_INDEX));
}
@NonNull
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return inflater.inflate(transitionDemo.layoutId, container, false);
}
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
View bgView = ButterKnife.findById(view, R.id.bg_view);
if (mTransitionDemo.colorId != 0 && bgView != null) {
bgView.setBackgroundColor(ContextCompat.getColor(getActivity(), mTransitionDemo.colorId));
if (transitionDemo.colorId != 0 && bgView != null) {
bgView.setBackgroundColor(ContextCompat.getColor(getActivity(), transitionDemo.colorId));
}
final int nextIndex = mTransitionDemo.ordinal() + 1;
final int nextIndex = transitionDemo.ordinal() + 1;
int buttonColor = 0;
if (nextIndex < TransitionDemo.values().length) {
buttonColor = TransitionDemo.fromIndex(nextIndex).colorId;
@@ -91,19 +97,17 @@ public class TransitionDemoController extends RefWatchingController {
buttonColor = TransitionDemo.fromIndex(0).colorId;
}
mBtnNext.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getActivity(), buttonColor)));
mContainerView = view;
mTvTitle.setText(mTransitionDemo.title);
btnNext.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getActivity(), buttonColor)));
tvTitle.setText(transitionDemo.title);
}
@NonNull
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return inflater.inflate(mTransitionDemo.layoutId, container, false);
protected String getTitle() {
return "Transition Demos";
}
@OnClick(R.id.btn_next) void onNextClicked() {
final int nextIndex = mTransitionDemo.ordinal() + 1;
final int nextIndex = transitionDemo.ordinal() + 1;
if (nextIndex < TransitionDemo.values().length) {
getRouter().pushController(getRouterTransaction(nextIndex, this));
@@ -113,12 +117,12 @@ public class TransitionDemoController extends RefWatchingController {
}
public ControllerChangeHandler getChangeHandler(Controller from) {
switch (mTransitionDemo) {
switch (transitionDemo) {
case VERTICAL:
return new VerticalChangeHandler();
case CIRCULAR:
TransitionDemoController demoController = (TransitionDemoController)from;
return new CircularRevealChangeHandler(demoController.mBtnNext, demoController.mContainerView);
return new CircularRevealChangeHandlerCompat(demoController.btnNext, demoController.containerView);
case FADE:
return new FadeChangeHandler();
case FLIP:
@@ -136,11 +140,10 @@ public class TransitionDemoController extends RefWatchingController {
public static RouterTransaction getRouterTransaction(int index, Controller fromController) {
TransitionDemoController toController = new TransitionDemoController(index);
ControllerChangeHandler changeHandler = toController.getChangeHandler(fromController);
return RouterTransaction.builder(toController)
.pushChangeHandler(changeHandler)
.popChangeHandler(changeHandler)
.build();
return RouterTransaction.with(toController)
.pushChangeHandler(toController.getChangeHandler(fromController))
.popChangeHandler(toController.getChangeHandler(fromController));
}
}
@@ -0,0 +1,51 @@
package com.bluelinelabs.conductor.demo.controllers.base;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.view.View;
import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.demo.ActionBarProvider;
public abstract class BaseController extends RefWatchingController {
protected BaseController() { }
protected BaseController(Bundle args) {
super(args);
}
// Note: This is just a quick demo of how an ActionBar *can* be accessed, not necessarily how it *should*
// be accessed. In a production app, this would use Dagger instead.
protected ActionBar getActionBar() {
ActionBarProvider actionBarProvider = ((ActionBarProvider)getActivity());
return actionBarProvider != null ? actionBarProvider.getSupportActionBar() : null;
}
@Override
protected void onAttach(@NonNull View view) {
setTitle();
super.onAttach(view);
}
protected void setTitle() {
Controller parentController = getParentController();
while (parentController != null) {
if (parentController instanceof BaseController && ((BaseController)parentController).getTitle() != null) {
return;
}
parentController = parentController.getParentController();
}
String title = getTitle();
ActionBar actionBar = getActionBar();
if (title != null && actionBar != null) {
actionBar.setTitle(title);
}
}
protected String getTitle() {
return null;
}
}
@@ -2,29 +2,42 @@ package com.bluelinelabs.conductor.demo.controllers.base;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.rxlifecycle.RxController;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public abstract class ButterKnifeController extends RxController {
private Unbinder unbinder;
protected ButterKnifeController() { }
protected ButterKnifeController(Bundle args) {
super(args);
}
protected abstract View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container);
@NonNull
@Override
protected void onBindView(@NonNull View view) {
super.onBindView(view);
ButterKnife.bind(this, view);
protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
View view = inflateView(inflater, container);
unbinder = ButterKnife.bind(this, view);
onViewBound(view);
return view;
}
protected void onViewBound(@NonNull View view) { }
@Override
protected void onUnbindView(View view) {
super.onUnbindView(view);
ButterKnife.unbind(this);
protected void onDestroyView(View view) {
super.onDestroyView(view);
unbinder.unbind();
unbinder = null;
}
}
}
@@ -2,9 +2,10 @@ package com.bluelinelabs.conductor.demo.controllers.base;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import com.bluelinelabs.conductor.demo.App;
import com.bluelinelabs.conductor.ControllerChangeHandler;
import com.bluelinelabs.conductor.ControllerChangeType;
import com.bluelinelabs.conductor.demo.DemoApplication;
public abstract class RefWatchingController extends ButterKnifeController {
@@ -13,21 +14,24 @@ public abstract class RefWatchingController extends ButterKnifeController {
super(args);
}
@Override
protected void onDetach(@NonNull View view) {
super.onDetach(view);
if (isDestroyed()) {
App.refWatcher.watch(view);
}
}
private boolean hasExited;
@Override
public void onDestroy() {
if (getView() != null) {
App.refWatcher.watch(getView());
super.onDestroy();
if (hasExited) {
DemoApplication.refWatcher.watch(this);
}
App.refWatcher.watch(this);
}
@Override
protected void onChangeEnded(@NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {
super.onChangeEnded(changeHandler, changeType);
hasExited = !changeType.isEnter;
if (isDestroyed()) {
DemoApplication.refWatcher.watch(this);
}
}
}
@@ -1,4 +1,4 @@
package com.bluelinelabs.conductor.demo;
package com.bluelinelabs.conductor.demo.util;
import android.os.Bundle;
import android.os.Parcelable;
@@ -9,164 +9,164 @@ import java.util.ArrayList;
public class BundleBuilder {
private final Bundle mBundle;
private final Bundle bundle;
public BundleBuilder(Bundle bundle) {
mBundle = bundle;
this.bundle = bundle;
}
public BundleBuilder putAll(Bundle bundle) {
mBundle.putAll(bundle);
this.bundle.putAll(bundle);
return this;
}
public BundleBuilder putBoolean(String key, boolean value) {
mBundle.putBoolean(key, value);
bundle.putBoolean(key, value);
return this;
}
public BundleBuilder putBooleanArray(String key, boolean[] value) {
mBundle.putBooleanArray(key, value);
bundle.putBooleanArray(key, value);
return this;
}
public BundleBuilder putDouble(String key, double value) {
mBundle.putDouble(key, value);
bundle.putDouble(key, value);
return this;
}
public BundleBuilder putDoubleArray(String key, double[] value) {
mBundle.putDoubleArray(key, value);
bundle.putDoubleArray(key, value);
return this;
}
public BundleBuilder putLong(String key, long value) {
mBundle.putLong(key, value);
bundle.putLong(key, value);
return this;
}
public BundleBuilder putLongArray(String key, long[] value) {
mBundle.putLongArray(key, value);
bundle.putLongArray(key, value);
return this;
}
public BundleBuilder putString(String key, String value) {
mBundle.putString(key, value);
bundle.putString(key, value);
return this;
}
public BundleBuilder putStringArray(String key, String[] value) {
mBundle.putStringArray(key, value);
bundle.putStringArray(key, value);
return this;
}
public BundleBuilder putBundle(String key, Bundle value) {
mBundle.putBundle(key, value);
bundle.putBundle(key, value);
return this;
}
public BundleBuilder putByte(String key, byte value) {
mBundle.putByte(key, value);
bundle.putByte(key, value);
return this;
}
public BundleBuilder putByteArray(String key, byte[] value) {
mBundle.putByteArray(key, value);
bundle.putByteArray(key, value);
return this;
}
public BundleBuilder putChar(String key, char value) {
mBundle.putChar(key, value);
bundle.putChar(key, value);
return this;
}
public BundleBuilder putCharArray(String key, char[] value) {
mBundle.putCharArray(key, value);
bundle.putCharArray(key, value);
return this;
}
public BundleBuilder putCharSequence(String key, CharSequence value) {
mBundle.putCharSequence(key, value);
bundle.putCharSequence(key, value);
return this;
}
public BundleBuilder putCharSequenceArray(String key, CharSequence[] value) {
mBundle.putCharSequenceArray(key, value);
bundle.putCharSequenceArray(key, value);
return this;
}
public BundleBuilder putCharSequenceArrayList(String key, ArrayList<CharSequence> value) {
mBundle.putCharSequenceArrayList(key, value);
bundle.putCharSequenceArrayList(key, value);
return this;
}
public BundleBuilder putInt(String key, int value) {
mBundle.putInt(key, value);
bundle.putInt(key, value);
return this;
}
public BundleBuilder putIntArray(String key, int[] value) {
mBundle.putIntArray(key, value);
bundle.putIntArray(key, value);
return this;
}
public BundleBuilder putFloat(String key, float value) {
mBundle.putFloat(key, value);
bundle.putFloat(key, value);
return this;
}
public BundleBuilder putFloatArray(String key, float[] value) {
mBundle.putFloatArray(key, value);
bundle.putFloatArray(key, value);
return this;
}
public BundleBuilder putIntegerArrayList(String key, ArrayList<Integer> value) {
mBundle.putIntegerArrayList(key, value);
bundle.putIntegerArrayList(key, value);
return this;
}
public BundleBuilder putParcelable(String key, Parcelable value) {
mBundle.putParcelable(key, value);
bundle.putParcelable(key, value);
return this;
}
public BundleBuilder putParcelableArray(String key, Parcelable[] value) {
mBundle.putParcelableArray(key, value);
bundle.putParcelableArray(key, value);
return this;
}
public BundleBuilder putParcelableArrayList(String key, ArrayList<? extends Parcelable> value) {
mBundle.putParcelableArrayList(key, value);
bundle.putParcelableArrayList(key, value);
return this;
}
public BundleBuilder putSerializable(String key, Serializable value) {
mBundle.putSerializable(key, value);
bundle.putSerializable(key, value);
return this;
}
public BundleBuilder putShort(String key, short value) {
mBundle.putShort(key, value);
bundle.putShort(key, value);
return this;
}
public BundleBuilder putShortArray(String key, short[] value) {
mBundle.putShortArray(key, value);
bundle.putShortArray(key, value);
return this;
}
public BundleBuilder putSparseParcelableArray(String key, SparseArray<? extends Parcelable> value) {
mBundle.putSparseParcelableArray(key, value);
bundle.putSparseParcelableArray(key, value);
return this;
}
public BundleBuilder putStringArrayList(String key, ArrayList<String> value) {
mBundle.putStringArrayList(key, value);
bundle.putStringArrayList(key, value);
return this;
}
public Bundle build() {
return mBundle;
return bundle;
}
}
@@ -16,13 +16,12 @@
package com.bluelinelabs.conductor.demo.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION_CODES;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import java.util.ArrayList;
@@ -33,8 +32,30 @@ import java.util.List;
* Applies an elasticity factor to reduce movement as you approach the given dismiss distance.
* Optionally also scales down content during drag.
*/
@TargetApi(VERSION_CODES.LOLLIPOP)
public class ElasticDragDismissFrameLayout extends FrameLayout {
public class ElasticDragDismissFrameLayout extends FrameLayout implements NestedScrollingParent {
public static abstract class ElasticDragDismissCallback {
/**
* Called for each drag event.
*
* @param elasticOffset Indicating the drag offset with elasticity applied i.e. may
* exceed 1.
* @param elasticOffsetPixels The elastically scaled drag distance in pixels.
* @param rawOffset Value from [0, 1] indicating the raw drag offset i.e.
* without elasticity applied. A value of 1 indicates that the
* dismiss distance has been reached.
* @param rawOffsetPixels The raw distance the user has dragged
*/
public void onDrag(float elasticOffset, float elasticOffsetPixels,
float rawOffset, float rawOffsetPixels) { }
/**
* Called when dragging is released and has exceeded the threshold dismiss distance.
*/
public void onDragDismissed() { }
}
// configurable attribs
private float dragDismissDistance = Float.MAX_VALUE;
@@ -51,21 +72,16 @@ public class ElasticDragDismissFrameLayout extends FrameLayout {
private List<ElasticDragDismissCallback> callbacks;
public ElasticDragDismissFrameLayout(Context context) {
this(context, null, 0, 0);
this(context, null, 0);
}
public ElasticDragDismissFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0, 0);
this(context, attrs, 0);
}
public ElasticDragDismissFrameLayout(Context context, AttributeSet attrs,
int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public ElasticDragDismissFrameLayout(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
super(context, attrs, defStyleAttr);
dragDismissDistance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());
dragDismissFraction = 0.7f;
@@ -73,29 +89,6 @@ public class ElasticDragDismissFrameLayout extends FrameLayout {
shouldScale = true;
}
public static abstract class ElasticDragDismissCallback {
/**
* Called for each drag event.
*
* @param elasticOffset Indicating the drag offset with elasticity applied i.e. may
* exceed 1.
* @param elasticOffsetPixels The elastically scaled drag distance in pixels.
* @param rawOffset Value from [0, 1] indicating the raw drag offset i.e.
* without elasticity applied. A value of 1 indicates that the
* dismiss distance has been reached.
* @param rawOffsetPixels The raw distance the user has dragged
*/
public void onDrag(float elasticOffset, float elasticOffsetPixels,
float rawOffset, float rawOffsetPixels) { }
/**
* Called when dragging is released and has exceeded the threshold dismiss distance.
*/
public void onDragDismissed() { }
}
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
return (nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0;
@@ -126,7 +119,7 @@ public class ElasticDragDismissFrameLayout extends FrameLayout {
.scaleX(1f)
.scaleY(1f)
.setDuration(200L)
.setInterpolator(AnimationUtils.loadInterpolator(getContext(), android.R.interpolator.fast_out_slow_in))
.setInterpolator(new FastOutSlowInInterpolator())
.setListener(null)
.start();
totalDrag = 0;
@@ -135,6 +128,24 @@ public class ElasticDragDismissFrameLayout extends FrameLayout {
}
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
return false;
}
@Override
public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
return false;
}
@Override
public int getNestedScrollAxes() {
return 0;
}
@Override
public void onNestedScrollAccepted(View child, View target, int axes) { }
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
@@ -171,6 +182,9 @@ public class ElasticDragDismissFrameLayout extends FrameLayout {
draggingUp = true;
if (shouldScale) setPivotY(0f);
}
setPivotX(getWidth() / 2);
// how far have we dragged relative to the distance to perform a dismiss
// (01 where 1 = dismiss distance). Decreasing logarithmically as we approach the limit
float dragFraction = (float) Math.log10(1 + (Math.abs(totalDrag) / dragDismissDistance));
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z"/>
</vector>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M16,11c1.66,0 2.99,-1.34 2.99,-3S17.66,5 16,5c-1.66,0 -3,1.34 -3,3s1.34,3 3,3zM8,11c1.66,0 2.99,-1.34 2.99,-3S9.66,5 8,5C6.34,5 5,6.34 5,8s1.34,3 3,3zM8,13c-2.33,0 -7,1.17 -7,3.5L1,19h14v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5zM16,13c-0.29,0 -0.62,0.02 -0.97,0.05 1.16,0.84 1.97,1.97 1.97,3.45L17,19h6v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5z"/>
</vector>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M12,2C8.13,2 5,5.13 5,9c0,5.25 7,13 7,13s7,-7.75 7,-13c0,-3.87 -3.13,-7 -7,-7zM12,11.5c-1.38,0 -2.5,-1.12 -2.5,-2.5s1.12,-2.5 2.5,-2.5 2.5,1.12 2.5,2.5 -1.12,2.5 -2.5,2.5z"/>
</vector>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="200dp"
android:layout_height="match_parent"
android:background="@color/grey_300"
/>
<FrameLayout
android:id="@+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
+26 -4
View File
@@ -1,9 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<com.bluelinelabs.conductor.ChangeHandlerFrameLayout
android:id="@+id/controller_container"
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bluelinelabs.conductor.demo.MainActivity"
/>
android:fitsSystemWindows="true"
tools:context="com.bluelinelabs.conductor.demo.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
</android.support.design.widget.AppBarLayout>
<com.bluelinelabs.conductor.ChangeHandlerFrameLayout
android:id="@+id/controller_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
@@ -14,17 +14,16 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="28sp"
android:textSize="22sp"
android:padding="16dp"
android:text="@string/drag_to_dismiss"
/>
<ScrollView
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:fillViewport="true"
android:nestedScrollingEnabled="true"
android:overScrollFooter="@android:color/transparent"
android:overScrollMode="never" >
@@ -36,7 +35,7 @@
android:padding="16dp"
/>
</ScrollView>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
</com.bluelinelabs.conductor.demo.widget.ElasticDragDismissFrameLayout>
+6 -1
View File
@@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/home_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
@@ -11,4 +10,10 @@
android:layout_height="match_parent"
/>
<FrameLayout
android:id="@+id/overlay_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="24dp"
android:background="@color/grey_300"
android:text="@string/rotate_for_two_pane"
/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/container_0"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<FrameLayout
android:id="@+id/container_1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<FrameLayout
android:id="@+id/container_2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
@@ -7,10 +7,11 @@
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="20sp"
android:layout_gravity="center"
android:gravity="center"
/>
<LinearLayout
@@ -48,4 +49,4 @@
</LinearLayout>
</FrameLayout>
</LinearLayout>
@@ -3,21 +3,21 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#88000000"
android:clickable="true" >
android:background="#88000000" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="32dp"
android:background="@android:color/white" >
android:background="@android:color/white">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="16dp"
/>
</FrameLayout>
@@ -3,16 +3,16 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green_300"
android:orientation="vertical" >
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="28sp"
android:padding="16dp"
android:text="@string/view_pager"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<android.support.v4.view.ViewPager
@@ -16,10 +16,10 @@
<ImageView
android:id="@+id/image_view"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_width="@dimen/display_target_image_size"
android:layout_height="@dimen/display_target_image_size"
android:layout_gravity="center_horizontal"
android:layout_margin="24dp"
android:layout_margin="@dimen/display_target_image_margin"
/>
<LinearLayout
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/row_root"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="24dp">
<TextView
android:id="@+id/tv_title"
style="@style/Base.TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>

Some files were not shown because too many files have changed in this diff Show More