├── .gitignore ├── .travis.yml ├── LICENSE ├── README-ZH.md ├── README.md ├── _config.yml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ └── fonts │ │ │ └── material-icon-font.ttf │ ├── java │ │ └── moe │ │ │ └── leer │ │ │ └── filetree │ │ │ ├── Extend.kt │ │ │ ├── MyApp.java │ │ │ ├── activity │ │ │ ├── AboutActivity.kt │ │ │ └── MainActivity.kt │ │ │ └── module │ │ │ ├── FileItem.java │ │ │ ├── FileTreeAdapter.java │ │ │ └── FileUtils.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_about.xml │ │ ├── activity_main.xml │ │ └── layout_file_tree_item.xml │ │ ├── menu │ │ └── main_menu.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── xyz │ └── leezoom │ └── tree2 │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screenshot ├── tree2view_demo1.png └── tree2view_demo2.png ├── settings.gradle └── treeview ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src ├── androidTest └── java │ └── xyz │ └── leezoom │ └── view │ └── treeview │ └── TreeViewTest.java ├── main ├── AndroidManifest.xml ├── java │ └── moe │ │ └── leer │ │ └── tree2view │ │ ├── TreeUtils.java │ │ ├── TreeView.java │ │ ├── adapter │ │ ├── SimpleTreeAdapter.java │ │ └── TreeAdapter.java │ │ └── module │ │ ├── DefaultTreeNode.java │ │ └── TreeNode.java └── res │ ├── layout │ └── layout_tree_item.xml │ └── values │ └── strings.xml └── test └── java └── xyz └── leezoom └── treeview └── TreeNodeTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | .DS_Store 5 | /build 6 | /captures 7 | .externalNativeBuild 8 | .idea/ 9 | app/libs/ 10 | app/src/androidTest/ 11 | libs/ 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: android 3 | jdk: oraclejdk8 4 | 5 | env: 6 | global: 7 | - ANDROID_TARGET=android-26 8 | - ANDROID_BUILD_TOOLS_VERSION=26.0.2 9 | - ANDROID_ABI=armeabi-v7a 10 | 11 | android: 12 | components: 13 | - tools 14 | - build-tools-$ANDROID_BUILD_TOOLS_VERSION 15 | - android-22 16 | - $ANDROID_TARGET 17 | - sys-img-armeabi-v7a-android-22 18 | - extra-android-m2repository 19 | - extra-android-support 20 | - extra 21 | licenses: 22 | - android-sdk-license-.+ 23 | 24 | before_install: 25 | - echo yes | android update sdk --all --filter build-tools-$ANDROID_BUILD_TOOLS_VERSION --no-ui --force 26 | 27 | before_script: 28 | - chmod +x gradlew 29 | 30 | script: 31 | - ./gradlew clean check test -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README-ZH.md: -------------------------------------------------------------------------------- 1 | # Tree2View 2 | 3 | 4 | 5 | [![](https://jitpack.io/v/LeeReindeer/Tree2View.svg)](https://jitpack.io/#LeeReindeer/Tree2View) 6 | 7 | > TreeView implementation in Android. 8 | 9 | ## 主要功能 10 | 11 | |Tree2View|文件管理器(一个例子)| 12 | |--------|----------| 13 | |①多级分层的树结构视图 | 基本的文件管理器布局| 14 | |②记忆展开状态 | 自动展开上次打开未关闭的目录| 15 | |③使用适配器设计模式,用户可自定义 TreeAdapter | 对不同类型的文件显示不同的Icon | 16 | |④动态增删节点 | 删除和添加文件后可自动刷新状态 | 17 | |⑤选择模式 | 长按节点进行文件操作(Copy, Cut, Rename, Delete) | 18 | |⑥动画支持,内置增删节点的动画 | 增删文件时带有动画 | 19 | 20 | [一个更简单的例子](https://github.com/LeeReindeer/Tree2View-demo) 21 | 22 | ## 实现原理 23 | 24 | - TreeView 继承自 ListView 25 | 26 | - DFS遍历可展开的树节点,转化为List 与 [TreeAdapter](https://github.com/LeeReindeer/Tree2View/blob/master/treeview/src/main/java/xyz/leezoom/view/treeview/adapter/TreeAdapter.java) 进行适配。 27 | 28 | - 分级的视觉效果通过 [SimpleTreeAdapter](https://github.com/LeeReindeer/Tree2View/blob/master/treeview/src/main/java/xyz/leezoom/view/treeview/adapter/SimpleTreeAdapter.java)(通过对不同深度的节点设置不同的**缩进**)来实现的。 29 | 30 | - 使用 [DefaultTreeNode](https://github.com/LeeReindeer/Tree2View/blob/master/treeview/src/main/java/xyz/leezoom/view/treeview/module/DefaultTreeNode.java) 来(用链表保存子节点)增删节点。这样就实现了视觉效果和数据结构统一的设计。 31 | 32 | ## 效果预览 - Preview 33 | 34 | ![](https://github.com/LeeReindeer/Tree2View/blob/master/screenshot/tree2view_demo1.png) 35 | 36 | ![](https://github.com/LeeReindeer/Tree2View/blob/master/screenshot/tree2view_demo2.png) 37 | 38 | ## 下载 39 | 40 | 1. 在项目的 build.gradle 中添加: 41 | 42 | ``` 43 | allprojects { 44 | repositories { 45 | ... 46 | maven { url 'https://jitpack.io' } 47 | } 48 | } 49 | ``` 50 | 51 | 2. 在 app 目录下的 build.gradle 添加: 52 | 53 | ``` 54 | dependencies { 55 | implementation 'com.github.LeeReindeer:Tree2View:v0.1.2' 56 | } 57 | ``` 58 | 59 | ## 使用 60 | 61 | 1. 在 `xml` 中添加,和 `ListView` 类似的. 62 | 63 | ```xml 64 | 71 | 72 | 73 | ``` 74 | 2. 在代码里添加初始化,这里使用Kotlin(Java 代码类似) 75 | 76 | ```kotlin 77 | var root :DefaultTreeNode? = DefaultTreeNode("Root") 78 | tree_view.root = root 79 | val child1 = DefaultTreeNode("Child1") 80 | val child2 = DefaultTreeNode("Child2") 81 | //在你创建节点之后,你需要立即添加她 82 | root.addChild(child1) 83 | root.addChild(child2) 84 | val child3 = DefaultTreeNode("Child3") 85 | child1.addChild(child3) 86 | //是否默认显示根节点的孩子 87 | tree_view.isRootVisible = true 88 | //默认的动画 89 | tree_view.isDefaultAnimation = true 90 | ``` 91 | 92 | 3. 设置监听器 93 | 94 | `Tree2View` 有默认的点击监听器,你也可以自己实现,可以参考[这里](https://github.com/LeeReindeer/Tree2View/blob/master/app/src/main/java/xyz/leezoom/tree2/activity/MainActivity.kt#L111)。 95 | 96 | 选择(长按)监听器需要自己实现。 97 | 98 | 4. 自定义使用 99 | 100 | 只需要实现 `TreeAapater` ,就那么简单。 101 | 102 | ```java 103 | public class FileTreeAdapter extends TreeAdapter { 104 | //resourceId 是 itemView 的 xml 视图。 105 | public FileTreeAdapter(Context context, DefaultTreeNode root, int resourceId) { 106 | super(context, root, resourceId); 107 | } 108 | 109 | @Override 110 | public View getView(int position, View convertView, ViewGroup parent) { 111 | //your code here 112 | //... 113 | //调用 setPadding 来设置缩进 114 | setPadding(holder.arrowIcon, depth, -1); 115 | //根据数据改变 view 的状态(比如图标什么的) 116 | toggle(node, holder); 117 | } 118 | 119 | @Override 120 | public void toggle(Object... objects) { 121 | //需要自己实现 122 | } 123 | } 124 | ``` 125 | 126 | 之后只要设置一下适配器: 127 | 128 | ```kotlin 129 | val adapter = FileTreeAdapter(this@MainActivity, root, R.layout.layout_file_tree_item) 130 | treeView.treeAdapter = adapter 131 | ``` 132 | 133 | ## License 134 | 135 | Apache 2.0 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tree2View 2 | 3 | 4 | 5 | [![](https://jitpack.io/v/LeeReindeer/Tree2View.svg)](https://jitpack.io/#LeeReindeer/Tree2View) 6 | 7 | > TreeView implementation in Android.Now available on Jitpack:tada: 8 | 9 | [中文版](/README-ZH.md) 10 | 11 | ## Features 12 | 13 | |TreeView|File Explorer(Advanced Example)| 14 | |--------|----------| 15 | |①Multi-level tree view | Basic file manager layout| 16 | |②Remember expansion state | Automatically expand the last unclosed directory| 17 | |③Customize TreeAdapter | Different types of documents show different Icon | 18 | |④Dynamic add and delete nodes | refresh status after delete and add files | 19 | |⑤Select listener | Long press node for file operations (Copy, Cut, Rename, Delete) | 20 | |⑥Animation support | Add or delete files with animation | 21 | 22 | You can also see [a more simple example](https://github.com/LeeReindeer/Tree2View-demo). 23 | 24 | ## Implement 25 | 26 | - TreeView extends from ListView. 27 | 28 | - DFS travel the expandable tree node, and convert it to List which adapt with [TreeAdapter](https://github.com/LeeReindeer/Tree2View/blob/master/treeview/src/main/java/xyz/leezoom/view/treeview/adapter/TreeAdapter.java). 29 | 30 | - Use [SimpleTreeAdapter](https://github.com/LeeReindeer/Tree2View/blob/master/treeview/src/main/java/xyz/leezoom/view/treeview/adapter/SimpleTreeAdapter.java) ot set different indentation on nodes of different depths. 31 | 32 | - Use LinkedList to store node's children, see [DefaultTreeNode](https://github.com/LeeReindeer/Tree2View/blob/master/treeview/src/main/java/xyz/leezoom/view/treeview/module/DefaultTreeNode.java). 33 | 34 | ## Preview 35 | 36 | ![](https://github.com/LeeReindeer/Tree2View/blob/master/screenshot/tree2view_demo1.png) 37 | 38 | ![](https://github.com/LeeReindeer/Tree2View/blob/master/screenshot/tree2view_demo2.png) 39 | 40 | ## Download 41 | 42 | 1. Add it in your root build.gradle at the end of repositories: 43 | 44 | ``` 45 | allprojects { 46 | repositories { 47 | ... 48 | maven { url 'https://jitpack.io' } 49 | } 50 | } 51 | ``` 52 | 53 | 2. Add the dependency 54 | 55 | ``` 56 | dependencies { 57 | implementation 'com.github.LeeReindeer:Tree2View:v0.1.2' 58 | } 59 | ``` 60 | 61 | ## Usage 62 | 63 | 1. Add in your xml: 64 | 65 | Feel free to use it as `ListView`. 66 | 67 | ```xml 68 | 75 | 76 | 77 | ``` 78 | 79 | 2. Add children in Kotlin code(Java is similar whit it) 80 | ```kotlin 81 | var root :DefaultTreeNode? = DefaultTreeNode("Root") 82 | tree_view.root = root 83 | val child1 = DefaultTreeNode("Child1") 84 | val child2 = DefaultTreeNode("Child2") 85 | // After create a node your should immediately add it. 86 | root.addChild(child1) 87 | root.addChild(child2) 88 | val child3 = DefaultTreeNode("Child3") 89 | child1.addChild(child3) 90 | //whether the root's children is expanded by default 91 | tree_view.isRootVisible = true 92 | //animation 93 | tree_view.isDefaultAnimation = true 94 | ``` 95 | 3. Add click listener and select listener 96 | 97 | Tree2View has a default click listener, but it's ok to add your own.You can refer to [here](https://github.com/LeeReindeer/Tree2View/blob/master/app/src/main/java/xyz/leezoom/tree2/activity/MainActivity.kt#L111). 98 | 99 | 4. If you want to use customized item view, you should implement `TreeAapater`, like this: 100 | ```java 101 | public class FileTreeAdapter extends TreeAdapter { 102 | //resourceId is your customized view resourceId, please use RelativeLayout, and let view neighbour. 103 | public FileTreeAdapter(Context context, DefaultTreeNode root, int resourceId) { 104 | super(context, root, resourceId); 105 | } 106 | 107 | @Override 108 | public View getView(int position, View convertView, ViewGroup parent) { 109 | //your code here 110 | //... 111 | //call padding for a better UI 112 | setPadding(holder.arrowIcon, depth, -1); 113 | //toggle your view's status here 114 | toggle(node, holder); 115 | } 116 | 117 | @Override 118 | public void toggle(Object... objects) { 119 | } 120 | ``` 121 | 122 | Then simply add: 123 | 124 | ```kotlin 125 | val adapter = FileTreeAdapter(this@MainActivity, root, R.layout.layout_file_tree_item) 126 | treeView.treeAdapter = adapter 127 | ``` 128 | 129 | ## License 130 | 131 | Apache 2.0 132 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | android { 8 | compileSdkVersion 28 9 | defaultConfig { 10 | applicationId "moe.leer.filetree" 11 | minSdkVersion 16 12 | targetSdkVersion 28 13 | versionCode 1 14 | versionName "1.0-beta" 15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | } 24 | 25 | dependencies { 26 | implementation fileTree(dir: 'libs', include: ['*.jar']) 27 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 28 | implementation 'com.android.support:appcompat-v7:28.0.0' 29 | implementation "org.jetbrains.anko:anko-common:$anko_version" 30 | implementation "org.jetbrains.anko:anko-sdk25:$anko_version" // sdk15, sdk19, sdk21, sdk23 are also available 31 | implementation "org.jetbrains.anko:anko-appcompat-v7:$anko_version" 32 | // Coroutine listeners for Anko Layouts 33 | implementation "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version" 34 | implementation "org.jetbrains.anko:anko-appcompat-v7-coroutines:$anko_version" 35 | 36 | implementation project(path: ':treeview') 37 | implementation 'com.github.johnkil.print:print:1.3.1' 38 | testImplementation 'junit:junit:4.12' 39 | } 40 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /app/src/main/assets/fonts/material-icon-font.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/assets/fonts/material-icon-font.ttf -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/Extend.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree 18 | 19 | import android.app.Activity 20 | import android.content.ActivityNotFoundException 21 | import android.content.Intent 22 | import android.net.Uri 23 | import android.os.Build 24 | import android.os.StrictMode 25 | import android.support.v4.app.ActivityCompat 26 | import android.webkit.MimeTypeMap 27 | import android.widget.Toast 28 | import moe.leer.filetree.module.FileItem 29 | import java.io.File 30 | 31 | 32 | fun Activity.requestPermission(permission: String, requestCode: Int) { 33 | ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode) 34 | } 35 | 36 | fun Activity.openFile(fileItem: FileItem) { 37 | //exposure file uri 38 | if (Build.VERSION.SDK_INT >= 24) { 39 | try { 40 | val m = StrictMode::class.java.getMethod("disableDeathOnFileUriExposure") 41 | m.invoke(null) 42 | } catch (e: Exception) { 43 | e.printStackTrace() 44 | } 45 | } 46 | val file = File(fileItem.absName) 47 | val myMime = MimeTypeMap.getSingleton() 48 | val newIntent = Intent(Intent.ACTION_VIEW) 49 | val mimeType = myMime.getMimeTypeFromExtension(file.extension) 50 | newIntent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK) 51 | newIntent.setDataAndType(Uri.fromFile(file), mimeType) 52 | 53 | 54 | try { 55 | startActivity(newIntent) 56 | } catch (e: ActivityNotFoundException) { 57 | Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show() 58 | } 59 | } 60 | 61 | fun File.isHideFile(): Boolean { 62 | return (this.name.indexOf(".") == 0) 63 | } 64 | 65 | fun File.copyTo(file: File) { 66 | this.inputStream().use { input -> 67 | file.outputStream().use { output -> 68 | input.copyTo(output) 69 | } 70 | } 71 | } 72 | 73 | fun File.moveTo(file: File) { 74 | //copy then delete this 75 | copyTo(file) 76 | this.delete() 77 | } 78 | 79 | fun File.getPrefixPath(): String { 80 | val abPath = this.absolutePath 81 | val index = abPath.lastIndexOf("/") 82 | //append "/" at last 83 | return abPath.substring(0, index + 1) 84 | } 85 | 86 | fun File.getNameWithoutType(): String { 87 | val fileName = this.name 88 | val index = fileName.lastIndexOf(".") 89 | if (index == -1 || index == 0) { 90 | return fileName 91 | } 92 | return fileName.substring(0, index) 93 | } 94 | 95 | fun File.getFileType(): String { 96 | val fileName = this.name 97 | val index = fileName.lastIndexOf(".") 98 | if (index == -1) { 99 | return "" 100 | } 101 | return fileName.substring(index + 1, fileName.length) 102 | } -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/MyApp.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree; 18 | 19 | import android.app.Application; 20 | 21 | import com.github.johnkil.print.PrintConfig; 22 | 23 | public class MyApp extends Application{ 24 | 25 | @Override 26 | public void onCreate() { 27 | super.onCreate(); 28 | PrintConfig.initDefault(getAssets(), "fonts/material-icon-font.ttf"); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/activity/AboutActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree.activity 18 | 19 | import android.content.pm.PackageInfo 20 | import android.content.pm.PackageManager 21 | import android.os.Bundle 22 | import android.support.v7.app.AppCompatActivity 23 | import kotlinx.android.synthetic.main.activity_about.* 24 | import org.jetbrains.anko.* 25 | import xyz.leezoom.tree2.R 26 | 27 | class AboutActivity : AppCompatActivity() { 28 | 29 | override fun onCreate(savedInstanceState: Bundle?) { 30 | super.onCreate(savedInstanceState) 31 | setContentView(R.layout.activity_about) 32 | about_version.text = "v" + getVersionName() 33 | about_page.setOnClickListener { 34 | browse(about_page.text.toString()) 35 | } 36 | about_me.setOnClickListener { 37 | browse("https://t.me/LeeReindeer") 38 | } 39 | 40 | about_icon.setOnClickListener { 41 | toast("You find me!\nHa ha...") 42 | browse("http://leezoom.xyz/2017/12/14/my_tree_view/") 43 | } 44 | } 45 | 46 | private fun getVersionName(): String { 47 | val manager = this.packageManager 48 | var info: PackageInfo? = null 49 | 50 | try { 51 | info = manager.getPackageInfo(this.packageName, 0) 52 | } catch (e: PackageManager.NameNotFoundException) { 53 | e.printStackTrace() 54 | } 55 | 56 | return info!!.versionName 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/activity/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree.activity 18 | 19 | import android.Manifest 20 | import android.content.pm.PackageManager 21 | import android.os.Bundle 22 | import android.os.Environment 23 | import android.support.v4.app.ActivityCompat 24 | import android.support.v7.app.AppCompatActivity 25 | import android.util.Log 26 | import android.view.Menu 27 | import android.view.MenuItem 28 | import android.view.View.GONE 29 | import android.view.View.VISIBLE 30 | import android.view.ViewGroup 31 | import android.view.animation.Animation 32 | import android.view.animation.AnimationUtils 33 | import android.widget.AdapterView 34 | import kotlinx.android.synthetic.main.activity_main.* 35 | import moe.leer.filetree.* 36 | import org.jetbrains.anko.* 37 | import xyz.leezoom.tree2.* 38 | import moe.leer.filetree.module.FileItem 39 | import moe.leer.filetree.module.FileTreeAdapter 40 | import moe.leer.filetree.module.FileUtils 41 | import moe.leer.tree2view.TreeUtils 42 | import moe.leer.tree2view.module.DefaultTreeNode 43 | import java.io.File 44 | 45 | @Suppress("PrivatePropertyName", "UNUSED_ANONYMOUS_PARAMETER") 46 | class MainActivity : AppCompatActivity() { 47 | 48 | private val TAG = "MainActivity" 49 | private val WRITE_EXTERNAL_STORAGE = 1 50 | 51 | private val INNER_STORAGE = Environment.getExternalStorageDirectory().absolutePath 52 | 53 | private val fileOps = listOf("Copy", "Cut", "Rename", "Delete") 54 | 55 | private var lastSelectedNode: DefaultTreeNode ? = null 56 | private var lastClickedFileName = "" 57 | //0 -> select, 1 -> copy, 2 -> cut 58 | private var selectedMod = 0 59 | private var hideMod = true 60 | 61 | private var adapter: FileTreeAdapter? = null 62 | private var root: DefaultTreeNode = DefaultTreeNode(FileItem(File(INNER_STORAGE))) 63 | // 64 | private var clickCount = HashMap() 65 | 66 | private var lastPress: Long = 0 67 | 68 | override fun onCreate(savedInstanceState: Bundle?) { 69 | super.onCreate(savedInstanceState) 70 | setContentView(R.layout.activity_main) 71 | 72 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 73 | != PackageManager.PERMISSION_GRANTED) { 74 | requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE) 75 | } else { 76 | initView() 77 | } 78 | 79 | //val list = TreeUtils.getVisibleNodesB(root) 80 | //for (item in list) Log.w(TAG, "bfs node " + (item.element).toString()) 81 | } 82 | 83 | private fun initRoot() { 84 | //expand root 85 | root.removeAllChildren() 86 | root.isExpanded = true 87 | root.element.name = "Internal storage" 88 | root.isSelectable = false 89 | val rootDir = File(INNER_STORAGE) 90 | val list = rootDir.listFiles() 91 | list.sort() 92 | //do not rm root node's children or add children 93 | clickCount.put(root.hashCode(), 1) 94 | for (item in list) { 95 | val n = DefaultTreeNode(FileItem(item)) 96 | n.isExpandable = item.isDirectory && n.isHasChildren 97 | if (!hideMod) { 98 | root.addChild(n) 99 | } else { 100 | if (!item.isHideFile()) { 101 | root.addChild(n) 102 | } 103 | } 104 | } 105 | } 106 | 107 | @Suppress("UNCHECKED_CAST") 108 | private fun initView() { 109 | initRoot() 110 | tree_view.requestLayout() 111 | adapter = FileTreeAdapter(this@MainActivity, root, R.layout.layout_file_tree_item) 112 | tree_view.treeAdapter = adapter 113 | tree_view.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> 114 | run { 115 | Log.d(TAG, "Clicked pos: $position") 116 | val nodes = adapter!!.nodesList 117 | //for (i in 0 until nodes.size) Log.i(TAG, "index: $i,node:" + (nodes[i].element as FileItem).name) 118 | //the click item 119 | val node: DefaultTreeNode = nodes[position] as DefaultTreeNode 120 | val c = if (clickCount[node.hashCode()] == null) 0 else clickCount[node.hashCode()] 121 | clickCount.put(node.hashCode(), c!! + 1) 122 | //remove children 123 | if (node.isExpanded) { 124 | //count visible child before remove 125 | //-1 for discount itself 126 | val visibleCount = TreeUtils.getVisibleNodesD(node).size - 1 127 | node.isExpanded = false 128 | Log.d(TAG, "onItemClick: close") 129 | //only remove and add node when first time click. 130 | if (c == 0) { 131 | node.removeAllChildren() 132 | } 133 | val offset = parent.firstVisiblePosition 134 | Log.d(TAG, "add view offset: $offset") 135 | val start = position - offset + 1 136 | for (i in start..if (start + visibleCount < tree_view.childCount) start + visibleCount - 1 else tree_view.childCount) { 137 | rmItemAnim(parent, i) 138 | } 139 | } else { 140 | //add children for this node 141 | node.isExpanded = true 142 | if (c == 0) { 143 | createNode(node) 144 | } 145 | //refresh nodes 146 | //nodes = TreeUtils.getVisibleNodesD(root) 147 | //for (i in 0 until nodes.size) Log.i(TAG, "index: $i,node:" + (nodes[i].element as FileItem).name) 148 | Log.d(TAG,"TreeView children: ${tree_view.childCount}") 149 | //update view 150 | adapter!!.nodesList = TreeUtils.getVisibleNodesD(root) 151 | //tree_view.refresh(null) 152 | adapter!!.notifyDataSetChanged() 153 | //start animation 154 | val offset = parent.firstVisiblePosition 155 | Log.d(TAG, "anim offset: $offset") 156 | val start = position - offset + 1 157 | Log.d(TAG, "anim start: $start") 158 | Log.d(TAG, "node size: ${node.size}") 159 | Log.d(TAG, "view count: ${tree_view.childCount}") 160 | val visibleCount = TreeUtils.getVisibleNodesD(node).size - 1 161 | Log.d(TAG, "visible count: $visibleCount") 162 | for (i in start..if (start + visibleCount <= tree_view.childCount) (start + visibleCount - 1) else tree_view.childCount) { 163 | Log.d(TAG, "anim index: $i") 164 | addItemAnim(parent, i) 165 | } 166 | //adapter!!.root = root 167 | Log.d(TAG, "onItemClick: open") 168 | } 169 | //only notify when you try to open an empty folder 170 | if (!node.isExpandable && node.element.isDir) { 171 | toast("Empty folder") 172 | } 173 | if (!node.element.isDir){ 174 | //open file in other app 175 | val fileItem: FileItem = node.element 176 | toast("Opening...") 177 | this.openFile(fileItem) 178 | } 179 | } 180 | } 181 | tree_view.setTreeItemSelectedListener { _, node, pos -> 182 | val list = TreeUtils.getVisibleNodesD(root) 183 | val fileItem: FileItem = list[pos].element as FileItem 184 | val file = File(fileItem.absName) 185 | toast("You selected " + fileItem.name) 186 | if (node.isSelectable) { 187 | when (selectedMod) { 188 | 0 -> { 189 | selector("File operations", fileOps, { dialogInterface, i -> 190 | run { 191 | lastSelectedNode = node as DefaultTreeNode? 192 | when (i) { 193 | 0 -> { 194 | Log.d(TAG, "Copy") 195 | toast("Selected a folder to copy to.") 196 | selectedMod = 1 197 | lastClickedFileName = fileItem.absName 198 | } 199 | 1 -> { 200 | Log.d(TAG, "Cut") 201 | toast("Selected a folder to move to.") 202 | selectedMod = 2 203 | lastClickedFileName = fileItem.absName 204 | } 205 | 2 -> { 206 | Log.d(TAG, "Rename") 207 | var reName: String 208 | alert { 209 | customView { 210 | title = "Rename:" 211 | //val edit = EditText(applicationContext) 212 | val editor = editText() 213 | editor.setText(file.getNameWithoutType()) 214 | okButton { 215 | reName = if (file.getFileType().isNotEmpty()) { 216 | editor.text.toString() + "." + file.getFileType() 217 | } else { //no file type 218 | editor.text.toString() 219 | } 220 | if (reName.isNotEmpty()) { 221 | FileUtils.doRename(fileItem.absName, reName) 222 | fileItem.name = reName 223 | list[pos].element = fileItem 224 | tree_view.refresh(list) 225 | } else { 226 | toast("Can't rename") 227 | } 228 | } 229 | cancelButton { } 230 | } 231 | }.show() 232 | } 233 | 3 -> { 234 | Log.d(TAG, "Delete") 235 | //File(fileItem.absName).delete() 236 | alert("Delete ${fileItem.name}") { 237 | yesButton { 238 | FileUtils.doDelete(fileItem.absName) 239 | node.removeThis() 240 | list.removeAt(pos) 241 | tree_view.refresh(list) 242 | } 243 | noButton { } 244 | }.show() 245 | } 246 | else -> { 247 | } 248 | } 249 | } 250 | }) 251 | } 252 | //select copy dest dir 253 | 1 -> { 254 | if (lastClickedFileName.isNotEmpty() && fileItem.isDir) { 255 | val source = File(lastClickedFileName) 256 | val dest = File(file, source.name) 257 | source.copyTo(dest) 258 | val newNode = DefaultTreeNode(FileItem(source)) 259 | node.addChild(newNode) 260 | list.add(newNode) 261 | list.remove(lastSelectedNode) 262 | lastSelectedNode!!.removeThis() 263 | tree_view.refresh(list) 264 | } else { 265 | toast("Can't copy") 266 | } 267 | lastClickedFileName = "" 268 | selectedMod = 0 269 | } 270 | //select cut dest dir 271 | 2 -> { 272 | if (lastClickedFileName.isNotEmpty() && fileItem.isDir) { 273 | val source = File(lastClickedFileName) 274 | val dest = File(file, source.name) 275 | source.moveTo(dest) 276 | val newNode = DefaultTreeNode(FileItem(source)) 277 | node.addChild(newNode) 278 | list.add(newNode) 279 | list.remove(lastSelectedNode) 280 | lastSelectedNode!!.removeThis() 281 | tree_view.refresh(list) 282 | } else { 283 | toast("Can't move") 284 | } 285 | lastClickedFileName = "" 286 | selectedMod = 0 287 | } 288 | } 289 | } 290 | false 291 | } 292 | tree_view.visibility = VISIBLE 293 | refresh_view.setOnRefreshListener { 294 | refreshTree() 295 | refresh_view.isRefreshing = false 296 | } 297 | } 298 | 299 | private fun refreshTree() { 300 | tree_view.visibility = GONE 301 | tree_view.treeAdapter.nodesList.clear() 302 | //adapter!!.notifyDataSetChanged() 303 | tree_view.refresh(null) 304 | initView() 305 | } 306 | 307 | private fun createNode(aNode: DefaultTreeNode) { 308 | val thisFile = File(aNode.element.absName) 309 | if (thisFile.listFiles() != null && thisFile.listFiles().isNotEmpty()) { 310 | val itemList = thisFile.listFiles() 311 | itemList.sort() 312 | for (file in itemList) { 313 | val n = DefaultTreeNode(FileItem(file)) 314 | n.isExpandable = file.isDirectory && n.isHasChildren 315 | if (hideMod) { 316 | if (!file.isHideFile()) { 317 | aNode.addChild(n) 318 | } 319 | } else { 320 | aNode.addChild(n) 321 | } 322 | } 323 | } 324 | } 325 | 326 | private fun addItemAnim(parent: ViewGroup, index: Int) { 327 | val anim = AnimationUtils.loadAnimation(this@MainActivity, android.R.anim.slide_in_left) 328 | anim.duration = 500 329 | //if (tree_view.getChildAt(index) != null) { 330 | // tree_view.getChildAt(index).startAnimation(anim) 331 | //} 332 | try { 333 | parent.getChildAt(index).startAnimation(anim) 334 | } catch (e: NullPointerException) { 335 | e.printStackTrace() 336 | Log.e(TAG, "null index: $index") 337 | } 338 | anim.setAnimationListener(object : Animation.AnimationListener { 339 | override fun onAnimationStart(animation: Animation) { 340 | } 341 | 342 | override fun onAnimationEnd(animation: Animation) { 343 | adapter!!.nodesList = TreeUtils.getVisibleNodesD(root) 344 | tree_view.refresh(null) 345 | } 346 | 347 | override fun onAnimationRepeat(animation: Animation) { 348 | } 349 | }) 350 | } 351 | 352 | private fun rmItemAnim(parent: ViewGroup, index: Int) { 353 | val anim = AnimationUtils.loadAnimation(this@MainActivity, android.R.anim.slide_out_right) 354 | anim.duration = 500 355 | try { 356 | parent.getChildAt(index).startAnimation(anim) 357 | } catch (e: NullPointerException) { 358 | e.printStackTrace() 359 | Log.e(TAG, "null index: $index") 360 | } 361 | anim.setAnimationListener(object : Animation.AnimationListener { 362 | override fun onAnimationStart(animation: Animation) { 363 | } 364 | 365 | override fun onAnimationEnd(animation: Animation) { 366 | adapter!!.nodesList = TreeUtils.getVisibleNodesD(root) 367 | tree_view.refresh(null) 368 | } 369 | 370 | override fun onAnimationRepeat(animation: Animation) { 371 | } 372 | }) 373 | } 374 | 375 | override fun onBackPressed() { 376 | val nowPress = System.currentTimeMillis() 377 | if (nowPress - lastPress > 1500) { 378 | toast(getString(R.string.hint_press_again)) 379 | lastPress = nowPress 380 | } else { 381 | finish() 382 | } 383 | } 384 | 385 | override fun onCreateOptionsMenu(menu: Menu?): Boolean { 386 | menuInflater.inflate(R.menu.main_menu, menu) 387 | return super.onCreateOptionsMenu(menu) 388 | } 389 | 390 | override fun onOptionsItemSelected(item: MenuItem?): Boolean { 391 | when (item!!.itemId) { 392 | R.id.hide_menu -> { 393 | hideMod = !hideMod 394 | toast("Hide Mode: $hideMod") 395 | runOnUiThread { 396 | refreshTree() 397 | } 398 | } 399 | R.id.about_menu -> { 400 | startActivity() 401 | } 402 | R.id.undo_menu -> { 403 | //just for cancel cut and copy 404 | if (selectedMod != 0) { 405 | selectedMod = 0 406 | val tip = if (selectedMod == 1) "Copy" else "Cut" 407 | toast("Cancel $tip $lastClickedFileName") 408 | lastClickedFileName = "" 409 | lastSelectedNode = null 410 | } else { 411 | toast("Can't undo") 412 | } 413 | } 414 | } 415 | return super.onOptionsItemSelected(item) 416 | } 417 | 418 | override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { 419 | when(requestCode) { 420 | WRITE_EXTERNAL_STORAGE -> { 421 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 422 | initView() 423 | } else { 424 | toast("Permission denied.") 425 | finish() 426 | } 427 | } 428 | else -> { 429 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 430 | } 431 | } 432 | 433 | } 434 | } -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/module/FileItem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree.module; 18 | 19 | import java.io.File; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | public class FileItem { 24 | 25 | private boolean isDir; 26 | private String name; 27 | private String absName; //full name = abstract path 28 | private long size; 29 | private String type; 30 | 31 | public static final String VIDEO = "video"; 32 | public static final String CODE = "code"; 33 | public static final String AUDIO = "audio"; 34 | public static final String ARCHIVE = "archive"; 35 | public static final String APK = "apk"; 36 | public static final String PIC = "picture"; 37 | public static final String DOC = "doc"; 38 | private static Map typeMap = new HashMap<>(); 39 | 40 | //init map 41 | //key -> suffix 42 | //value -> type 43 | static { 44 | String[] video = {"3gp", "asf", "avi", "mp4", "mpe", "mpeg", "mpg", "mpg4", "m4u", "m4v", "mov", "rmvb"}; 45 | for (String s : video) { 46 | typeMap.put(s, "video"); 47 | } 48 | 49 | String[] text = {"txt", "xml", "conf", "prop", "cpp", "h", "java", "class", "log", "json", "js", 50 | "php", "css", "py", "c", "c++", "cfg", "ini", "bat", "mf", "mtd", "lua", "html", "htm", "kt"}; 51 | for (String s : text) { 52 | typeMap.put(s, "code"); 53 | } 54 | 55 | String[] doc = {"doc", "md", "xls", "xlsx", "ppt", "pptx", "pdf"}; 56 | for (String s : doc) { 57 | typeMap.put(s, "doc"); 58 | } 59 | 60 | String[] audio = {"m3u", "m4a", "m4b", "m4p", "mp2", "mp3", "mpga", "ogg", "wav", "wma", "wmv", "3gpp", "flac", "amr"}; 61 | for (String s : audio) { 62 | typeMap.put(s, "audio"); 63 | } 64 | 65 | String[] pic = {"jpg", "jpeg", "png", "gif", "webp", "exif", "tiff", "bmp", "psd", "svg"}; 66 | for (String s : pic) { 67 | typeMap.put(s, "picture"); 68 | } 69 | 70 | String[] archive = {"zip", "rar", "7z", "tar", "jar", "gz", "xz"}; 71 | for (String s : archive) { 72 | typeMap.put(s, "archive"); 73 | } 74 | typeMap.put("apk", "apk"); 75 | } 76 | 77 | public FileItem(File file) { 78 | this.isDir = file.isDirectory(); 79 | this.absName = file.getAbsolutePath(); 80 | this.size = getSize(); 81 | this.name = file.getName(); 82 | this.type = getMinType(); 83 | } 84 | 85 | @Deprecated 86 | public FileItem(String absName) { 87 | this.absName = absName; 88 | } 89 | 90 | public boolean isDir() { 91 | return isDir; 92 | } 93 | 94 | public void setDir(boolean dir) { 95 | isDir = dir; 96 | } 97 | 98 | public String getAbsName() { 99 | return absName; 100 | } 101 | 102 | public void setAbsName(String absName) { 103 | this.absName = absName; 104 | } 105 | 106 | public String getName() { 107 | int lastNameIndex = absName.lastIndexOf("/"); 108 | return name = absName.substring(lastNameIndex + 1); 109 | } 110 | 111 | //just for display 112 | public void setName(String name) { 113 | this.name = name; 114 | this.absName = FileUtils.getPrefixPath(this.absName) + name; 115 | } 116 | 117 | public long getSize() { 118 | return size; 119 | } 120 | 121 | public String getType() { 122 | return type; 123 | } 124 | 125 | public void setType(String type) { 126 | this.type = type; 127 | } 128 | 129 | private String getMinType() { 130 | int dotIndex = name.lastIndexOf("."); 131 | if (dotIndex == -1 || dotIndex == name.length()) { 132 | return ""; 133 | } 134 | String fileSuffix = name.substring(dotIndex + 1).toLowerCase(); 135 | return typeMap.containsKey(fileSuffix) ? typeMap.get(fileSuffix) : fileSuffix; 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/module/FileTreeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree.module; 18 | 19 | import android.content.Context; 20 | import android.view.LayoutInflater; 21 | import android.view.View; 22 | import android.view.ViewGroup; 23 | import android.widget.TextView; 24 | 25 | import com.github.johnkil.print.PrintView; 26 | 27 | import xyz.leezoom.tree2.R; 28 | import moe.leer.tree2view.TreeUtils; 29 | import moe.leer.tree2view.adapter.TreeAdapter; 30 | import moe.leer.tree2view.module.DefaultTreeNode; 31 | 32 | public class FileTreeAdapter extends TreeAdapter { 33 | 34 | public FileTreeAdapter(Context context, DefaultTreeNode root, int resourceId) { 35 | super(context, root, resourceId); 36 | } 37 | 38 | @SuppressWarnings("RedundantCast") 39 | @Override 40 | public View getView(int position, View convertView, ViewGroup parent) { 41 | if (mNodesList == null) { 42 | mNodesList = TreeUtils.getVisibleNodesD(super.mRoot); 43 | notifyDataSetChanged(); 44 | } 45 | DefaultTreeNode node = mNodesList.get(position); 46 | ViewHolder holder; 47 | 48 | if (convertView == null) { 49 | convertView = LayoutInflater.from(mContext).inflate(mResourceId, parent, false); 50 | holder = new ViewHolder(); 51 | holder.arrowIcon = (PrintView) convertView.findViewById(R.id.arrow_icon); 52 | holder.itemIcon = (PrintView) convertView.findViewById(R.id.item_icon); 53 | holder.fileText = (TextView) convertView.findViewById(R.id.ft_name); 54 | convertView.setTag(holder); 55 | } else { 56 | holder = (ViewHolder) convertView.getTag(); 57 | } 58 | FileItem fileItem = (FileItem)(node.getElement()); 59 | //get the file name(not the full name) 60 | holder.fileText.setText(fileItem.getName()); 61 | if (fileItem.isDir()) { 62 | //set dir icon 63 | holder.itemIcon.setIconText(getStringResource(R.string.ic_folder)); 64 | } else { 65 | //set file icon 66 | switch (fileItem.getType()) { 67 | case FileItem.APK: 68 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_apk)); 69 | break; 70 | case FileItem.ARCHIVE: 71 | holder.itemIcon.setIconText(getStringResource(R.string.ic_archive)); 72 | break; 73 | case FileItem.AUDIO: 74 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_audio)); 75 | break; 76 | case FileItem.CODE: 77 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_code)); 78 | break; 79 | case FileItem.VIDEO: 80 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_video)); 81 | break; 82 | case FileItem.PIC: 83 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_image)); 84 | break; 85 | case FileItem.DOC: 86 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_document)); 87 | break; 88 | default: 89 | holder.itemIcon.setIconText(getStringResource(R.string.ic_drive_file)); 90 | break; 91 | } 92 | } 93 | int depth = node.getDepth(); 94 | setPadding(holder.arrowIcon, depth, -1); 95 | toggle(node, holder); 96 | return convertView; 97 | } 98 | 99 | 100 | @Override 101 | public void toggle(Object... objects) { 102 | DefaultTreeNode node = null; 103 | ViewHolder holder = null; 104 | try { 105 | node = (DefaultTreeNode) objects[0]; 106 | holder = (ViewHolder) objects[1]; 107 | } catch (ClassCastException e) { 108 | e.printStackTrace(); 109 | } 110 | //only toggle for dir 111 | if (node.isExpandable()) { 112 | if (!node.isExpanded()) { 113 | //set right arrowIcon 114 | holder.arrowIcon.setIconText(getStringResource(R.string.ic_keyboard_arrow_right)); 115 | } else if (node.isExpanded()) { 116 | //set down arrowIcon 117 | holder.arrowIcon.setIconText(getStringResource(R.string.ic_keyboard_arrow_down)); 118 | } 119 | } else { 120 | //holder.arrowIcon.setVisibility(View.GONE); 121 | holder.arrowIcon.setIconText(getStringResource(R.string.ic_keyboard_arrow_right)); 122 | } 123 | } 124 | 125 | private String getStringResource(int id) { 126 | if (mContext == null) { 127 | throw new IllegalStateException("Context is null"); 128 | } 129 | return mContext.getResources().getString(id); 130 | } 131 | 132 | class ViewHolder { 133 | PrintView arrowIcon; 134 | PrintView itemIcon; 135 | TextView fileText; 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /app/src/main/java/moe/leer/filetree/module/FileUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.filetree.module; 18 | 19 | import android.os.Build; 20 | import android.support.annotation.RequiresApi; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.nio.file.Files; 25 | 26 | /** 27 | * Author: lee 28 | * Time: 12/16/17. 29 | */ 30 | public class FileUtils { 31 | 32 | public static String getNameFromAbsolutePath(String abPath) { 33 | int index = abPath.lastIndexOf("/"); 34 | return abPath.substring(index + 1, abPath.length()); 35 | } 36 | 37 | public static String getPrefixPath(String abPath) { 38 | int index = abPath.lastIndexOf("/"); 39 | //append "/" at last 40 | return abPath.substring(0, index + 1); 41 | } 42 | 43 | public static String getFileType(String fileName) { 44 | int index = fileName.lastIndexOf("."); 45 | return fileName.substring(index + 1, fileName.length()); 46 | } 47 | 48 | public static boolean doRename(String abPath, String reName) { 49 | return new File(abPath).renameTo(new File(getPrefixPath(abPath) + reName)); 50 | } 51 | 52 | @RequiresApi(api = Build.VERSION_CODES.O) 53 | public static void doMove(String source, String dest) throws IOException { 54 | //copy then delete 55 | copy(source, dest); 56 | doDelete(source); 57 | } 58 | 59 | public static boolean doDelete(String abPath) { 60 | return new File(abPath).delete(); 61 | } 62 | 63 | @RequiresApi(api = Build.VERSION_CODES.O) 64 | public static void copy(File origin, File dest) throws IOException { 65 | Files.copy(origin.toPath(), dest.toPath()); 66 | } 67 | 68 | @RequiresApi(api = Build.VERSION_CODES.O) 69 | public static void copy(String fromPath, String toPath) throws IOException { 70 | File from = new File(fromPath); 71 | File to = new File(toPath); 72 | Files.copy(from.toPath(), to.toPath()); 73 | } 74 | 75 | public static void main(String[] args) { 76 | String ab = "Home/Lee/Pic/lee.jpg"; 77 | String name = getNameFromAbsolutePath(ab); 78 | System.out.println(getFileType(name)); 79 | System.out.println(getNameFromAbsolutePath(ab)); 80 | System.out.println(getPrefixPath(ab)); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_about.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 24 | 25 | 29 | 30 | 35 | 36 | 42 | 43 | 50 | 51 | 52 | 53 | 63 | 64 | 75 | 76 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 19 | 23 | 24 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_file_tree_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 23 | 24 | 34 | 35 | 46 | 47 | 55 | 56 | -------------------------------------------------------------------------------- /app/src/main/res/menu/main_menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 20 | 21 | 25 | 26 | 30 | 31 | 35 | 36 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #12558C 4 | #12558E 5 | #12558C 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Tree2View 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | Hide/Show 439 | About 440 | Press angin to exit 441 | https://github.com/LeeReindeer/Tree2View 442 | This is Tree2View example. 443 | Contact me: \nhttps://t.me/LeeReindeer 444 | Undo 445 | 446 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/xyz/leezoom/tree2/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.leezoom.tree2 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.2.71' 5 | ext.anko_version = '0.10.3' 6 | repositories { 7 | google() 8 | jcenter() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.2.1' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 14 | 15 | // NOTE: Do not place your application dependencies here; they belong 16 | // in the individual module build.gradle files 17 | } 18 | } 19 | 20 | allprojects { 21 | repositories { 22 | google() 23 | jcenter() 24 | maven { url 'https://jitpack.io' } 25 | } 26 | } 27 | 28 | task clean(type: Delete) { 29 | delete rootProject.buildDir 30 | } 31 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | #org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | #org.gradle.jvmargs=-DsocksProxyHost=127.0.0.1 -DsocksProxyPort=1080 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 03 18:48:15 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /screenshot/tree2view_demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/screenshot/tree2view_demo1.png -------------------------------------------------------------------------------- /screenshot/tree2view_demo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeReindeer/Tree2View/d59d50169b6a4214f9dee3473c0314c0fd745807/screenshot/tree2view_demo2.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':treeview' 2 | -------------------------------------------------------------------------------- /treeview/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /treeview/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.library' 18 | apply plugin: 'com.github.dcendents.android-maven' 19 | 20 | group='com.github.LeeReindeer' 21 | 22 | android { 23 | compileSdkVersion 28 24 | 25 | 26 | 27 | defaultConfig { 28 | minSdkVersion 16 29 | targetSdkVersion 28 30 | versionCode 1 31 | versionName "0.1.2" 32 | 33 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 34 | 35 | } 36 | 37 | buildTypes { 38 | release { 39 | minifyEnabled false 40 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 41 | } 42 | } 43 | 44 | } 45 | 46 | dependencies { 47 | implementation fileTree(dir: 'libs', include: ['*.jar']) 48 | 49 | testImplementation 'junit:junit:4.12' 50 | androidTestImplementation 'junit:junit:4.12' 51 | } 52 | -------------------------------------------------------------------------------- /treeview/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /treeview/src/androidTest/java/xyz/leezoom/view/treeview/TreeViewTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package xyz.leezoom.view.treeview; 18 | 19 | import android.content.Context; 20 | 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | 24 | import static org.junit.Assert.assertEquals; 25 | 26 | //@RunWith(AndroidJunit4.class) 27 | public class TreeViewTest { 28 | 29 | private Context instrumentationCtx; 30 | 31 | @Before 32 | public void setup() { 33 | //instrumentationCtx = InstrumentationRegistry.getContext(); 34 | } 35 | 36 | @Test 37 | public void adapterShouldNonNull() { 38 | //SimpleTreeAdapter adapter = new SimpleTreeAdapter() 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /treeview/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 19 | -------------------------------------------------------------------------------- /treeview/src/main/java/moe/leer/tree2view/TreeUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.tree2view; 18 | 19 | import android.util.Pair; 20 | 21 | import java.util.ArrayList; 22 | import java.util.LinkedList; 23 | import java.util.Queue; 24 | import java.util.Stack; 25 | 26 | import moe.leer.tree2view.module.DefaultTreeNode; 27 | import moe.leer.tree2view.module.TreeNode; 28 | 29 | @SuppressWarnings({"unchecked", "WeakerAccess", "unused"}) 30 | public class TreeUtils { 31 | 32 | /** 33 | * Recursive DFS 34 | * Return all the size of the aRoot(tree or sub tree) 35 | */ 36 | @SuppressWarnings({"unchecked", "Duplicates"}) 37 | public static Pair travelNodes(DefaultTreeNode aRoot) { 38 | int size = 0; 39 | int depth = 0; 40 | //System.out.println("Size: " + first.getChildren().size()); 41 | for (int j = 0; j < aRoot.getChildren().size(); j++) { 42 | DefaultTreeNode nextNode = (DefaultTreeNode) aRoot.getChildren().get(j); 43 | //count tree size 44 | size++; 45 | if (nextNode.isHasChildren()) { 46 | //count tree depth 47 | depth++; 48 | travelNodes(nextNode); 49 | } 50 | } 51 | return new Pair<>(size, depth); 52 | } 53 | 54 | /** 55 | * DFS use Stack 56 | */ 57 | public static ArrayList getVisibleNodesD(DefaultTreeNode aRoot) { 58 | ArrayList list = new ArrayList<>(); 59 | Stack stack = new Stack<>(); 60 | if (aRoot == null) { 61 | return null; 62 | } 63 | stack.push(aRoot); 64 | while (!stack.isEmpty()) { 65 | DefaultTreeNode node = stack.pop(); 66 | list.add(node); 67 | LinkedList children = node.getChildren(); 68 | if (children == null) { 69 | continue; 70 | } 71 | //add children in reversed order 72 | for (int i = children.size() - 1; i >= 0; i--) { 73 | if (node.isExpanded()) { 74 | stack.push(children.get(i)); 75 | } 76 | } 77 | } 78 | return list; 79 | } 80 | 81 | /** 82 | * DFS, same as 83 | * @see TreeUtils#getVisibleNodesD(DefaultTreeNode) 84 | * @see DefaultTreeNode#getPathFromRoot 85 | * Get all children nodes(contains the given node). 86 | */ 87 | public static ArrayList getAllNodesD(DefaultTreeNode aRoot) { 88 | ArrayList list = new ArrayList<>(); 89 | Stack stack = new Stack<>(); 90 | if (aRoot == null) { 91 | return null; 92 | } 93 | stack.push(aRoot); 94 | while (!stack.isEmpty()) { 95 | DefaultTreeNode node = stack.pop(); 96 | list.add(node); 97 | LinkedList children = node.getChildren(); 98 | if (children == null) { 99 | continue; 100 | } 101 | //add children in reversed order 102 | for (int i = children.size() - 1; i >= 0; i--) { 103 | stack.push(children.get(i)); 104 | } 105 | } 106 | return list; 107 | } 108 | 109 | /** 110 | * BFS use Queue 111 | * @return ArrayList of DefaultTreeNode 112 | */ 113 | public static ArrayList getVisibleNodesB(DefaultTreeNode aRoot) { 114 | Queue> q = new LinkedList<>(); 115 | if (aRoot == null) { 116 | return null; 117 | } 118 | ArrayList list = new ArrayList<>(); 119 | q.add(aRoot); 120 | while (!q.isEmpty()) { 121 | DefaultTreeNode node = q.remove(); 122 | list.add(node); 123 | LinkedList children = node.getChildren(); 124 | if (children == null) { 125 | continue; 126 | } 127 | //add expanded node's children 128 | if (node.isExpanded()) { 129 | for (DefaultTreeNode n : children) { 130 | q.add(n); 131 | } 132 | } 133 | } 134 | return list; 135 | } 136 | 137 | /** 138 | * BFS 139 | * Get all children nodes(contains the given node). 140 | */ 141 | public static ArrayList getAllNodesB(DefaultTreeNode aRoot) { 142 | Queue> q = new LinkedList<>(); 143 | if (aRoot == null) { 144 | return null; 145 | } 146 | ArrayList list = new ArrayList<>(); 147 | q.add(aRoot); 148 | while (!q.isEmpty()) { 149 | DefaultTreeNode node = q.remove(); 150 | list.add(node); 151 | LinkedList children = node.getChildren(); 152 | if (children == null) { 153 | continue; 154 | } 155 | for (DefaultTreeNode n : children) { 156 | q.add(n); 157 | } 158 | } 159 | return list; 160 | } 161 | 162 | public static TreeNode getNodeAtIndex(DefaultTreeNode node, int index) { 163 | if (node == null || index < 0) { 164 | return null; 165 | } 166 | //use dfs index 167 | return getAllNodesD(node).get(index); 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /treeview/src/main/java/moe/leer/tree2view/TreeView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.tree2view; 18 | 19 | import android.content.Context; 20 | import android.util.AttributeSet; 21 | import android.util.Log; 22 | import android.view.View; 23 | import android.view.ViewGroup; 24 | import android.view.animation.Animation; 25 | import android.view.animation.AnimationUtils; 26 | import android.widget.AdapterView; 27 | import android.widget.ListView; 28 | 29 | import java.util.ArrayList; 30 | import java.util.HashMap; 31 | 32 | import moe.leer.tree2view.adapter.SimpleTreeAdapter; 33 | import moe.leer.tree2view.adapter.TreeAdapter; 34 | import moe.leer.tree2view.module.DefaultTreeNode; 35 | import moe.leer.tree2view.module.TreeNode; 36 | import xyz.leezoom.view.treeview.R; 37 | 38 | @SuppressWarnings("unused") 39 | public class TreeView extends ListView { 40 | 41 | private static final String TAG = "TreeView"; 42 | 43 | private Context mContext; 44 | 45 | //same ad TreeModel in JTree 46 | private TreeAdapter adapter; 47 | //track node's expand status 48 | private HashMap, Boolean> expandStatusMap = new HashMap<>(); 49 | 50 | private onChildSelectedListener selectedListener; 51 | 52 | //The number of DefaultTreeNode in tree, root is already size in. 53 | protected int size = 1; 54 | 55 | //Tree depth 56 | protected int depth = 1; 57 | 58 | //The root node 59 | protected DefaultTreeNode root; 60 | 61 | protected boolean isRootVisible = true; 62 | 63 | protected boolean defaultAnimation = true; 64 | 65 | private StringBuilder sb = new StringBuilder(); 66 | 67 | private ArrayList searchList = new ArrayList<>(); 68 | //record the node's expanded status 69 | private HashMap expandedState; 70 | 71 | public TreeView(Context context) { 72 | super(context); 73 | init(context, null); 74 | } 75 | 76 | public TreeView(Context context, DefaultTreeNode root) { 77 | super(context); 78 | init(context, root); 79 | } 80 | 81 | public TreeView(Context context, TreeAdapter adapter) { 82 | super(context); 83 | this.mContext = context; 84 | this.adapter = adapter; 85 | } 86 | 87 | public TreeView(Context context, AttributeSet attrs) { 88 | super(context, attrs); 89 | init(context, null); 90 | } 91 | 92 | public TreeView(Context context, AttributeSet attrs, int defStyleAttr) { 93 | super(context, attrs, defStyleAttr); 94 | init(context, null); 95 | } 96 | 97 | private void init(Context context, DefaultTreeNode root) { 98 | this.mContext = context; 99 | if (root == null) { 100 | return; 101 | } 102 | if (this.root == null || this.root != root) { 103 | setTreeAdapter(new SimpleTreeAdapter(mContext, root, R.layout.layout_tree_item)); 104 | } 105 | this.setOnItemClickListener(new OnTreeItemClickListener()); 106 | } 107 | 108 | public String travelTree() { 109 | return travelTree(root); 110 | } 111 | 112 | public String travelTree(DefaultTreeNode parent) { 113 | //reset 114 | depth = 1; 115 | size = 1; 116 | //reset sb 117 | sb = new StringBuilder(); 118 | DefaultTreeNode node; 119 | if (parent == null) { 120 | node = root; 121 | } else { 122 | node = parent; 123 | } 124 | 125 | return root.getElement() + "->" + travelNodeList(node); 126 | } 127 | 128 | /** 129 | * DFS travel tree. 130 | * @param first the parent node 131 | * @return string of nodes list 132 | */ 133 | @SuppressWarnings({"unchecked", "Duplicates"}) 134 | public String travelNodeList(DefaultTreeNode first) { 135 | //System.out.println("Size: " + first.getChildren().size()); 136 | sb.append("{ "); 137 | for (int j = 0; j < first.getChildren().size(); j++) { 138 | DefaultTreeNode nextNode = (DefaultTreeNode) first.getChildren().get(j); 139 | sb.append(nextNode.getElement().toString()); 140 | if (!nextNode.isHasChildren()) { 141 | sb.append(", "); 142 | } 143 | //count tree size 144 | size++; 145 | if (nextNode.isHasChildren()) { 146 | //count tree depth 147 | depth++; 148 | sb.append("->"); 149 | travelNodeList(nextNode); 150 | } 151 | } 152 | sb.append("}, "); 153 | return sb.toString(); 154 | } 155 | 156 | /** 157 | * BFS travel tree. 158 | * Get all TreeNodes in tree 159 | * @return array of TreeNode 160 | */ 161 | public TreeNode[] getFullPath() { 162 | return (TreeNode[]) TreeUtils.getAllNodesB(root).toArray(); 163 | } 164 | 165 | public ArrayList search(Object e) { 166 | searchList.clear(); 167 | return searchElement(e, root); 168 | } 169 | 170 | @SuppressWarnings({"Duplicates", "unchecked"}) 171 | private ArrayList searchElement(Object e, DefaultTreeNode first) { 172 | for (int j = 0; j < first.getChildren().size(); j++) { 173 | DefaultTreeNode nextNode = (DefaultTreeNode) first.getChildren().get(j); 174 | //sb.append(nextNode.getElement().toString()); 175 | if (nextNode.getElement() == e) { 176 | searchList.add(nextNode); 177 | } 178 | if (nextNode.isHasChildren()) { 179 | //search next node 180 | searchElement(e, nextNode); 181 | } 182 | } 183 | return searchList; 184 | } 185 | 186 | /*getters and setters.start*/ 187 | public int getSize() { 188 | size = TreeUtils.travelNodes(root).first; 189 | return size; 190 | } 191 | 192 | public int getDepth() { 193 | //size depth 194 | depth = TreeUtils.travelNodes(root).second; 195 | return depth; 196 | } 197 | 198 | public void setRoot(DefaultTreeNode root) { 199 | init(mContext, root); 200 | } 201 | 202 | public DefaultTreeNode getRoot() { 203 | return root; 204 | } 205 | /*getters and setters.end*/ 206 | 207 | public boolean isRootVisible() { 208 | return isRootVisible; 209 | } 210 | 211 | public void setRootVisible(boolean rootVisible) { 212 | isRootVisible = rootVisible; 213 | root.setExpanded(rootVisible); 214 | } 215 | 216 | public void setTreeAdapter(TreeAdapter adapter) { 217 | this.adapter = adapter; 218 | //call super 219 | this.setAdapter(adapter); 220 | this.root = adapter.getRoot(); 221 | //expanded root node to show it's children 222 | this.root.setExpanded(isRootVisible); 223 | } 224 | 225 | public TreeAdapter getTreeAdapter() { 226 | return adapter; 227 | } 228 | 229 | public void refresh(ArrayList nodes) { 230 | if (adapter == null) { 231 | throw new NullPointerException("adapter is null"); 232 | } 233 | if (nodes != null) { 234 | adapter.setNodesList(nodes); 235 | } 236 | adapter.notifyDataSetChanged(); 237 | } 238 | 239 | public boolean isDefaultAnimation() { 240 | return defaultAnimation; 241 | } 242 | 243 | public void setDefaultAnimation(boolean animation) { 244 | defaultAnimation = animation; 245 | } 246 | 247 | @Override 248 | public void setOnItemLongClickListener(OnItemLongClickListener listener) { 249 | final ArrayList nodes = TreeUtils.getAllNodesD(root); 250 | //if (nodes == null || nodes.isEmpty()) { 251 | // return; 252 | //} 253 | super.setOnItemLongClickListener(new OnItemLongClickListener() { 254 | @Override 255 | public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { 256 | return selectedListener != null && selectedListener.onTreeItemSelected(view, nodes.get(position), position); 257 | } 258 | }); 259 | } 260 | 261 | public onChildSelectedListener getSelectedListener() { 262 | return selectedListener; 263 | } 264 | 265 | public void setTreeItemSelectedListener(onChildSelectedListener selectedListener) { 266 | this.selectedListener = selectedListener; 267 | setOnItemLongClickListener(null); 268 | } 269 | 270 | @Override 271 | public String toString() { 272 | return travelTree(root); 273 | } 274 | 275 | public interface onChildSelectedListener { 276 | boolean onTreeItemSelected(View v, DefaultTreeNode node, int pos); 277 | } 278 | 279 | /** 280 | * Implement ItemClickListener, and can't be extended. 281 | */ 282 | class OnTreeItemClickListener implements AdapterView.OnItemClickListener { 283 | 284 | DefaultTreeNode root; 285 | TreeAdapter mAdapter; 286 | int ADD_ANIM = 0x10; 287 | int RM_ANIM = 0x11; 288 | 289 | OnTreeItemClickListener() { 290 | this.mAdapter = adapter; 291 | this.root = TreeView.this.root; 292 | } 293 | 294 | void addAnimation(int type, ViewGroup parent, int index) { 295 | Animation anim = null; 296 | if (type == ADD_ANIM) { 297 | anim = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left); 298 | } else if (type == RM_ANIM) { 299 | anim = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_out_right); 300 | } 301 | assert anim != null; 302 | anim.setDuration(500); 303 | 304 | try { 305 | //FIXME NULL POINT 306 | parent.getChildAt(index).startAnimation(anim); 307 | } catch (NullPointerException e) { 308 | e.printStackTrace(); 309 | Log.e(TAG, "null index: " + index); 310 | } 311 | 312 | anim.setAnimationListener(new Animation.AnimationListener() { 313 | @Override 314 | public void onAnimationStart(Animation animation) { 315 | } 316 | 317 | @Override 318 | public void onAnimationEnd(Animation animation) { 319 | //notify change 320 | adapter.setNodesList(TreeUtils.getVisibleNodesD(root)); 321 | TreeView.this.refresh(null); 322 | } 323 | 324 | @Override 325 | public void onAnimationRepeat(Animation animation) { 326 | } 327 | }); 328 | } 329 | 330 | void startAnimation(int type, AdapterView parent, int position, int visibleCount) { 331 | int offset = parent.getFirstVisiblePosition(); 332 | int start = position - offset + 1; 333 | int end = (start + visibleCount) <= parent.getChildCount() ? (start + visibleCount - 1) : parent.getChildCount(); 334 | for (int i = start; i <= end; i++) { 335 | addAnimation(type, parent, i); 336 | } 337 | } 338 | 339 | /** 340 | * Lazy load.Click to toggle view, will call this: 341 | * @see SimpleTreeAdapter#getView(int, View, ViewGroup) 342 | * to refresh view 343 | */ 344 | @SuppressWarnings("unchecked") 345 | @Override 346 | public void onItemClick(AdapterView parent, View view, int position, long id) { 347 | ArrayList nodes = adapter.getNodesList(); 348 | //the click item 349 | DefaultTreeNode node = nodes.get(position); 350 | Log.d(TAG, "onItemClick: " + node.getElement().toString()); 351 | if (!node.isHasChildren()) { 352 | Log.w(TAG, "onItemClick: not Expandable"); 353 | } else { 354 | //toggle 355 | if (node.isExpanded()) { 356 | //close 357 | int visibleCount = TreeUtils.getVisibleNodesD(node).size() - 1; 358 | Log.d(TAG, "onItemClick, visibleCount: " + visibleCount); 359 | node.setExpanded(false); 360 | Log.d(TAG, "onItemClick: close"); 361 | if (defaultAnimation) { 362 | //start animation before view update 363 | startAnimation(RM_ANIM, parent, position, visibleCount); 364 | } else { 365 | adapter.setNodesList(TreeUtils.getVisibleNodesD(root)); 366 | TreeView.this.refresh(null); 367 | } 368 | } else { 369 | //open 370 | node.setExpanded(true); 371 | Log.d(TAG, "onItemClick: open"); 372 | //update view 373 | adapter.setNodesList(TreeUtils.getVisibleNodesD(root)); 374 | TreeView.this.refresh(null); 375 | if (defaultAnimation) { 376 | //start animation after view update 377 | int visibleCount = TreeUtils.getVisibleNodesD(node).size() - 1; 378 | Log.d(TAG, "onItemClick, visibleCount: " + visibleCount); 379 | //FIXME NULL 380 | startAnimation(ADD_ANIM, parent, position, visibleCount); 381 | } 382 | } 383 | } 384 | } 385 | 386 | } 387 | 388 | } 389 | -------------------------------------------------------------------------------- /treeview/src/main/java/moe/leer/tree2view/adapter/SimpleTreeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.tree2view.adapter; 18 | 19 | import android.content.Context; 20 | import android.view.LayoutInflater; 21 | import android.view.View; 22 | import android.view.ViewGroup; 23 | import android.widget.TextView; 24 | 25 | import xyz.leezoom.view.treeview.R; 26 | import moe.leer.tree2view.TreeUtils; 27 | import moe.leer.tree2view.module.DefaultTreeNode; 28 | 29 | public class SimpleTreeAdapter extends TreeAdapter { 30 | 31 | public SimpleTreeAdapter(Context context, DefaultTreeNode root, int resourceId) { 32 | super(context, root, resourceId); 33 | } 34 | 35 | @SuppressWarnings({"RedundantCast", "StatementWithEmptyBody", "UnusedAssignment"}) 36 | @Override 37 | public View getView(int position, View convertView, ViewGroup parent) { 38 | //dfs travel when first time called 39 | if (mNodesList == null) { 40 | mNodesList = TreeUtils.getVisibleNodesD(super.mRoot); 41 | notifyDataSetChanged(); 42 | } 43 | DefaultTreeNode node = mNodesList.get(position); 44 | ViewHolder holder = null; 45 | 46 | if (convertView == null) { 47 | convertView = LayoutInflater.from(mContext).inflate(mResourceId, parent, false); 48 | holder = new ViewHolder(); 49 | holder.tv = (TextView) convertView.findViewById(R.id.default_tree_item); 50 | convertView.setTag(holder); 51 | } else { 52 | holder = (ViewHolder) convertView.getTag(); 53 | } 54 | holder.tv.setText(node.getElement().toString()); 55 | int depth = node.getDepth(); 56 | //set view indent 57 | setPadding(holder.tv, depth, -1); 58 | //toggle 59 | //toggle(holder, node); 60 | return convertView; 61 | } 62 | 63 | @Override 64 | public void toggle(Object... objects) { 65 | try { 66 | DefaultTreeNode node = (DefaultTreeNode) objects[0]; 67 | ViewHolder holder = (ViewHolder) objects[1]; 68 | if (node.isHasChildren() && !node.isExpanded()) { 69 | //set your icon 70 | } else if (node.isHasChildren() && node.isExpanded()) { 71 | //set your icon 72 | } 73 | } catch (ClassCastException e ) { 74 | e.printStackTrace(); 75 | } 76 | } 77 | 78 | class ViewHolder { 79 | TextView tv; 80 | } 81 | } 82 | /* 83 | convertView = new FrameLayout(mContext); 84 | FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 100); 85 | convertView.setLayoutParams(layoutParams); 86 | holder = new ViewHolder(); 87 | holder.tv = new TextView(mContext); 88 | holder.tv.setLayoutParams(layoutParams); 89 | 90 | convertView.setTag(holder); 91 | */ -------------------------------------------------------------------------------- /treeview/src/main/java/moe/leer/tree2view/adapter/TreeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.tree2view.adapter; 18 | 19 | import android.content.Context; 20 | import android.view.View; 21 | import android.widget.BaseAdapter; 22 | 23 | import java.util.ArrayList; 24 | 25 | import moe.leer.tree2view.module.DefaultTreeNode; 26 | 27 | /** 28 | * Extend this class to set your own TreeModel 29 | * T can be your data 30 | */ 31 | @SuppressWarnings("WeakerAccess") 32 | public abstract class TreeAdapter extends BaseAdapter { 33 | 34 | //root node 35 | protected DefaultTreeNode mRoot; 36 | protected Context mContext; 37 | protected ArrayList mNodesList; 38 | 39 | protected int mResourceId; 40 | 41 | protected int baseIndent = 50; 42 | 43 | public TreeAdapter(Context mContext) { 44 | this.mContext = mContext; 45 | } 46 | 47 | public TreeAdapter(Context context, DefaultTreeNode root) { 48 | this.mRoot = root; 49 | this.mContext= context; 50 | } 51 | 52 | public TreeAdapter(Context context, DefaultTreeNode root, int resourceId) { 53 | this.mRoot = root; 54 | this.mContext = context; 55 | this.mResourceId = resourceId; 56 | } 57 | 58 | /** 59 | * @return return the direct children'number of root 60 | */ 61 | @Override 62 | public int getCount() { 63 | if (mNodesList != null) { 64 | return mNodesList.size(); 65 | } else { 66 | return mRoot.getVisibleSize() + 1; 67 | } 68 | } 69 | 70 | @Override 71 | public Object getItem(int position) { 72 | if (mNodesList != null) { 73 | return mNodesList.get(position); 74 | } 75 | return null; 76 | } 77 | 78 | @Override 79 | public long getItemId(int position) { 80 | return position; 81 | } 82 | 83 | protected void setPadding(View v, int depth, int indent) { 84 | if (v == null || depth < 0) { 85 | throw new IllegalArgumentException("illegal params"); 86 | } 87 | if (indent < 0) { 88 | indent = baseIndent; 89 | } 90 | v.setPadding(indent * (depth + 1), 91 | v.getPaddingTop(), 92 | v.getPaddingRight(), 93 | v.getPaddingBottom()); 94 | } 95 | 96 | /** 97 | * Toggle your object's status 98 | * @param objects objects to toggle 99 | */ 100 | public abstract void toggle(Object ... objects); 101 | 102 | //public abstract View createView(TreeNode node, Object content); 103 | 104 | public ArrayList getNodesList() { 105 | return mNodesList; 106 | } 107 | 108 | public void setNodesList(ArrayList mNodesList) { 109 | this.mNodesList = mNodesList; 110 | } 111 | 112 | public DefaultTreeNode getRoot() { 113 | return mRoot; 114 | } 115 | 116 | public void setRoot(DefaultTreeNode node) { 117 | this.mRoot = node; 118 | } 119 | 120 | public int getResourceId() { 121 | return mResourceId; 122 | } 123 | 124 | public void setResourceId(int mResourceId) { 125 | this.mResourceId = mResourceId; 126 | } 127 | } -------------------------------------------------------------------------------- /treeview/src/main/java/moe/leer/tree2view/module/DefaultTreeNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.tree2view.module; 18 | 19 | import java.io.Serializable; 20 | import java.util.LinkedList; 21 | import java.util.NoSuchElementException; 22 | 23 | /** 24 | * Author: lee 25 | * Time: 12/4/17. 26 | */ 27 | @SuppressWarnings({"WeakerAccess", "unchecked", "unused", "UnusedAssignment", "RedundantCast"}) 28 | public class DefaultTreeNode implements TreeNode, Serializable, Cloneable{ 29 | 30 | //max = 1 << 31 31 | private int id; 32 | private int lastId; 33 | 34 | //The content of this node 35 | private transient E element; 36 | private DefaultTreeNode parent = null; 37 | 38 | //array of node's child 39 | private LinkedList children; 40 | 41 | //just a mark, even node has children, 42 | //this value can still be false. 43 | boolean hasChildren = false; 44 | //same as hasChildren, but it's default value is true. 45 | //it let an expandable node can add children, after add the hasChildren will be true 46 | private boolean mExpandable = true; 47 | //whether this node is expanded, always false when (mExpandable == false) 48 | private boolean isExpanded = false; 49 | private boolean mSelectable = true; 50 | private boolean isSelected = false; 51 | 52 | //children size 53 | private int size; 54 | @SuppressWarnings("FieldCanBeLocal") 55 | private int depth; 56 | 57 | public DefaultTreeNode(E element) { 58 | this.element = element; 59 | this.hasChildren = false; 60 | } 61 | 62 | public DefaultTreeNode(E element, boolean hasChildren) { 63 | this.hasChildren = hasChildren; 64 | this.element = element; 65 | } 66 | 67 | public DefaultTreeNode(DefaultTreeNode parent, E element) { 68 | this.parent = parent; 69 | this.element = element; 70 | 71 | this.hasChildren = false; 72 | } 73 | 74 | public DefaultTreeNode(DefaultTreeNode parent, LinkedList children, E element) { 75 | this.parent = parent; 76 | this.children = children; 77 | for (TreeNode n : children) { 78 | n.setParent(this); 79 | } 80 | this.element = element; 81 | this.hasChildren = true; 82 | } 83 | 84 | //generate id for it's direct children 85 | private int generateId() { 86 | return ++lastId; 87 | } 88 | 89 | /** 90 | * Add child to this node at last in list. 91 | * @param child the child 92 | */ 93 | public void addChild(TreeNode child) { 94 | if (child == null) { 95 | throw new NullPointerException("Child can't be null"); 96 | } else if (isAncestorOf((DefaultTreeNode) child)) { 97 | throw new IllegalArgumentException("child can't be the ancestor of this node"); 98 | } 99 | if (children == null) { 100 | children = new LinkedList<>(); 101 | this.hasChildren = mExpandable = true; 102 | } 103 | size++; 104 | child.setParent(this); 105 | ((DefaultTreeNode) child).depth = this.depth + 1; 106 | ((DefaultTreeNode) child).id = generateId(); 107 | children.add((DefaultTreeNode) child); 108 | } 109 | 110 | /** 111 | * Insert child at the index 112 | * @param index index to insert(after insert the child node's index is index) 113 | * @param child the given child 114 | */ 115 | public void addChild(int index, DefaultTreeNode child) { 116 | if (child == null) { 117 | throw new NullPointerException("Child can't be null"); 118 | } else if (isAncestorOf((DefaultTreeNode) child)) { 119 | throw new IllegalArgumentException("child can't be the ancestor of this node"); 120 | } 121 | if (children == null) { 122 | children = new LinkedList<>(); 123 | this.hasChildren = mExpandable = true; 124 | } 125 | size ++; 126 | child.setParent(this); 127 | child.depth = this.depth + 1; 128 | child.id = generateId(); 129 | children.add(index, (DefaultTreeNode) child); 130 | } 131 | 132 | /** 133 | * Add a number of children 134 | * @param children the children 135 | */ 136 | public void addChildren(DefaultTreeNode...children) { 137 | for (TreeNode child : children) { 138 | addChild(child); 139 | } 140 | } 141 | 142 | @SuppressWarnings("SuspiciousMethodCalls") 143 | @Override 144 | public void removeChild(TreeNode child) { 145 | if (child == null) { 146 | throw new IllegalArgumentException("given child is null"); 147 | } 148 | if (!children.contains(child)) { 149 | throw new IllegalArgumentException("is not the child of this"); 150 | } 151 | size--; 152 | children.remove(child); 153 | } 154 | 155 | @Override 156 | public void removeThis() { 157 | TreeNode parent = this.getParent(); 158 | if (parent != null) { //not the root node 159 | this.getParent().removeChild(this); 160 | } else { 161 | throw new IllegalStateException("can not remove root node"); 162 | } 163 | //remove children 164 | this.children = null; 165 | //unlink from parent 166 | this.parent = null; 167 | this.size = 0; 168 | this.hasChildren = mExpandable = false; 169 | } 170 | 171 | public void removeAllChildren() { 172 | this.children = null; 173 | this.hasChildren = false; 174 | this.size = 0; 175 | } 176 | 177 | public void removeFromParent(TreeNode parent, TreeNode child) { 178 | if (parent == null || child == null) { 179 | throw new IllegalArgumentException("parent or child is null"); 180 | } 181 | parent.removeChild(child); 182 | } 183 | 184 | /*getters & setters*/ 185 | 186 | public E getElement() { 187 | return element; 188 | } 189 | 190 | public void setElement(E element) { 191 | this.element = element; 192 | } 193 | 194 | public TreeNode getParent() { 195 | return parent; 196 | } 197 | 198 | public void setParent(TreeNode parent) { 199 | this.parent = (DefaultTreeNode) parent; 200 | } 201 | 202 | public TreeNode getFirstNode() { 203 | if (!hasChildren) { 204 | throw new NoSuchElementException("node has no children"); 205 | } 206 | return children.getFirst(); 207 | } 208 | 209 | public TreeNode getLastNode() { 210 | if (!hasChildren) { 211 | throw new NoSuchElementException("node has no children"); 212 | } 213 | return children.getLast(); 214 | } 215 | 216 | public int getSize() { 217 | return size; 218 | } 219 | 220 | 221 | /** 222 | * 223 | * @return the expanded nodes count 224 | */ 225 | public int getVisibleSize() { 226 | int c = 0; 227 | for (DefaultTreeNode child : children) { 228 | if (child.isExpanded()) { 229 | ++c; 230 | } 231 | } 232 | return c; 233 | } 234 | 235 | /** 236 | * Return number of this node's depth. 237 | * Bug: After create a node your should immediately add it. 238 | * depth is auto increase at: 239 | * @see #addChild(TreeNode), so is this cheaper to get depth? 240 | * @return node's depth 241 | */ 242 | public int getDepth() { 243 | //int d = 0; 244 | //TreeNode thisNode = this; 245 | //while ((thisNode = thisNode.getParent()) != null) { 246 | // d++; 247 | //} 248 | //depth = d; 249 | if (this.parent == null) { //the root node 250 | depth = 0; 251 | } 252 | return depth; 253 | } 254 | 255 | public LinkedList getChildren() { 256 | return children; 257 | } 258 | 259 | public TreeNode getChildAt(int index) { 260 | if (children == null) { 261 | throw new NullPointerException("this node has no children"); 262 | } 263 | return children.get(index); 264 | } 265 | 266 | /** 267 | * Set the children for this node, this will replace before children. 268 | * @param children the children to be added. 269 | */ 270 | public void setChildren(LinkedList children) { 271 | if (children != null) { 272 | this.hasChildren = true; 273 | for (TreeNode n : children) { 274 | n.setParent(this); 275 | } 276 | size+=children.size(); 277 | this.children = children; 278 | } 279 | } 280 | 281 | public void setExpandable(boolean mExpandable) { 282 | this.mExpandable = mExpandable; 283 | } 284 | 285 | public boolean isExpandable() { 286 | return mExpandable; 287 | } 288 | 289 | public boolean isExpanded() { 290 | return isExpanded; 291 | } 292 | 293 | public void setExpanded(boolean expanded) { 294 | isExpanded = expanded; 295 | } 296 | 297 | public boolean isSelectable() { 298 | return mSelectable; 299 | } 300 | 301 | public void setSelectable(boolean mSelectable) { 302 | this.mSelectable = mSelectable; 303 | } 304 | 305 | public boolean isSelected() { 306 | return isSelected; 307 | } 308 | 309 | public void setSelected(boolean selected) { 310 | isSelected = selected; 311 | } 312 | 313 | /** 314 | * If a node has no children, the node is called a leaf 315 | * @return true if has no children 316 | */ 317 | @Override 318 | public boolean isLeaf() { 319 | return !isHasChildren(); 320 | } 321 | 322 | public int getLeafCount() { 323 | return getLeafCountOf(this); 324 | } 325 | 326 | protected int getLeafCountOf(DefaultTreeNode aNode) { 327 | int c = 0; 328 | LinkedList list = aNode.getChildren(); 329 | DefaultTreeNode node = null; 330 | if (list != null) { 331 | for (int i = 0; i < list.size(); i++) { 332 | node = list.get(i); 333 | if (!node.hasChildren) { 334 | c++; 335 | } else { //node has children 336 | c += getLeafCountOf(node); 337 | } 338 | } 339 | } 340 | return c; 341 | } 342 | 343 | public boolean isHasChildren() { 344 | return hasChildren; 345 | } 346 | 347 | public void setHasChildren(boolean hasChildren) { 348 | this.hasChildren = hasChildren; 349 | } 350 | 351 | public boolean isRoot() { 352 | return parent == null; 353 | } 354 | 355 | private void increaseId(DefaultTreeNode node) { 356 | node.id = this.id + 1; 357 | } 358 | 359 | /** 360 | * public method to Get path from root 361 | * @return string of element path 362 | */ 363 | public String getPath() { 364 | DefaultTreeNode[] nodes = (DefaultTreeNode[]) getPathFromRoot(this, 0); 365 | StringBuilder sb = new StringBuilder(); 366 | if (nodes == null) { 367 | return "Root/"; 368 | } 369 | for (DefaultTreeNode e : nodes) { 370 | sb.append(e.getElement().toString()).append("/"); 371 | } 372 | return sb.toString(); 373 | } 374 | 375 | /*getters & setters*/ 376 | 377 | /** 378 | * //@see javax.swing.tree.DefaultMutableTreeNode#getPathToRoot 379 | * @param node always this node 380 | * @param depth use to specialise array size 381 | * @return array of DefaultTreeNode 382 | */ 383 | @Override 384 | @SuppressWarnings({"Duplicates", "unchecked", "ConstantConditions"}) 385 | public TreeNode[] getPathFromRoot(TreeNode node, int depth) { 386 | 387 | DefaultTreeNode[] treeNodes; 388 | // root's parent node 389 | if (node == null) { 390 | if (depth == 0) { 391 | return null; 392 | } else { 393 | return treeNodes = new DefaultTreeNode[depth]; 394 | } 395 | } else { 396 | depth++; 397 | treeNodes = (DefaultTreeNode[]) getPathFromRoot(node.getParent(), depth); 398 | //Add root in treeNodes[0], and... 399 | treeNodes[treeNodes.length - depth] = (DefaultTreeNode) node; 400 | } 401 | return treeNodes; 402 | } 403 | 404 | /** 405 | * Check this node whether the descendant of given node. 406 | */ 407 | public boolean isDescendantOf(DefaultTreeNode gNode) { 408 | if (gNode == null) { 409 | return false; 410 | } 411 | 412 | TreeNode a = this; 413 | do { 414 | if (a == gNode) { 415 | return true; 416 | } 417 | } while ((a = a.getParent()) != null); 418 | 419 | return false; 420 | } 421 | 422 | /** 423 | * Check this node whether the ancestor of given node 424 | */ 425 | public boolean isAncestorOf(DefaultTreeNode gNode) { 426 | return gNode != null && gNode.isDescendantOf(this); 427 | } 428 | 429 | @Override 430 | public String toString() { 431 | if (element == null) { 432 | return ""; 433 | } 434 | return element.toString(); 435 | } 436 | 437 | @Override 438 | protected Object clone() throws CloneNotSupportedException { 439 | try { 440 | DefaultTreeNode node = (DefaultTreeNode) super.clone(); 441 | node.hasChildren = this.hasChildren; 442 | node.element = this.element; 443 | node.mSelectable = this.mSelectable; 444 | node.isSelected = this.isSelected; 445 | node.isExpanded = this.isExpanded; 446 | node.children = (LinkedList) this.children.clone(); 447 | return node; 448 | } catch (Exception ignored) { 449 | } 450 | return null; 451 | } 452 | 453 | // TODO: 12/14/17 implements Serializable 454 | } 455 | -------------------------------------------------------------------------------- /treeview/src/main/java/moe/leer/tree2view/module/TreeNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package moe.leer.tree2view.module; 18 | 19 | public interface TreeNode { 20 | 21 | void addChild(TreeNode child); 22 | 23 | void removeChild(TreeNode child); 24 | 25 | /** 26 | * Remove this node and all it's children(if it has) 27 | */ 28 | void removeThis(); 29 | 30 | void setParent(TreeNode node); 31 | 32 | TreeNode getParent(); 33 | 34 | boolean isLeaf(); 35 | 36 | TreeNode[] getPathFromRoot(TreeNode node, int depth); 37 | 38 | } 39 | -------------------------------------------------------------------------------- /treeview/src/main/res/layout/layout_tree_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 24 | 25 | 33 | 34 | -------------------------------------------------------------------------------- /treeview/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | TreeView 19 | 20 | -------------------------------------------------------------------------------- /treeview/src/test/java/xyz/leezoom/treeview/TreeNodeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 LeeReindeer 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package xyz.leezoom.treeview; 18 | 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | 22 | import moe.leer.tree2view.module.DefaultTreeNode; 23 | 24 | import static org.junit.Assert.assertEquals; 25 | 26 | public class TreeNodeTest { 27 | 28 | private DefaultTreeNode root = new DefaultTreeNode<>("Root"); 29 | private DefaultTreeNode child1 = new DefaultTreeNode<>("child1"); 30 | private DefaultTreeNode child2 = new DefaultTreeNode<>("child2"); 31 | private DefaultTreeNode child3 = new DefaultTreeNode<>("child3"); 32 | 33 | 34 | @Before 35 | public void init() { 36 | root.addChildren(child1, child2); 37 | child1.addChild(child3); 38 | } 39 | 40 | @Test 41 | public void shouldAutoIncreaseDepth() { 42 | int depth = 0; 43 | depth++; 44 | assertEquals(depth, child1.getDepth()); 45 | depth++; 46 | assertEquals(depth, child3.getDepth()); 47 | } 48 | 49 | @Test 50 | public void rootShouldNotHasParent() { 51 | assertEquals(null, root.getParent()); 52 | } 53 | 54 | @Test 55 | public void ancestorAndDescendantTest() { 56 | //child3.addChild(root); 57 | boolean isAncestor = child1.isAncestorOf(child3); 58 | boolean isDescendant = child2.isDescendantOf(child1); 59 | assertEquals(true, isAncestor); 60 | assertEquals(false, isDescendant); 61 | isAncestor = child3.isAncestorOf(child1); 62 | assertEquals(false, isAncestor); 63 | isDescendant = child3.isDescendantOf(child1); 64 | assertEquals(true, isDescendant); 65 | } 66 | 67 | @Test 68 | public void shouldRemoveItself() { 69 | child1.removeThis(); 70 | int size = root.getSize(); 71 | assertEquals(1, size); 72 | assertEquals(false, root.isAncestorOf(child1)); 73 | } 74 | 75 | } 76 | --------------------------------------------------------------------------------