├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── flowlayout ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── nex3z │ │ │ └── flowlayout │ │ │ ├── FlowAdapter.java │ │ │ └── FlowLayout.java │ └── res │ │ └── values │ │ └── attrs.xml │ └── test │ └── java │ └── com │ └── nex3z │ └── flowlayout │ └── ExampleUnitTest.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images └── sample.png ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── nex3z │ │ └── flowlayout │ │ └── flowlayout │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── nex3z │ │ │ └── flowlayout │ │ │ └── sample │ │ │ ├── MainActivity.java │ │ │ ├── RecyclerViewActivity.java │ │ │ ├── SimpleAdapter.java │ │ │ └── SimpleFlowAdapter.java │ └── res │ │ ├── drawable │ │ ├── box.xml │ │ ├── label_bg.xml │ │ └── label_bg2.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_recycler_view.xml │ │ ├── item.xml │ │ └── item_label.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── arrays.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── nex3z │ └── flowlayout │ └── flowlayout │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea 4 | /local.properties 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FlowLayout 2 | 3 | A FlowLayout for Android, which allows child views flow to next row when there is no enough space. The spacing between child views can be calculated by the FlowLayout so that the views are evenly placed. 4 | 5 |

6 | 7 |

8 | 9 | 10 | ## Gradle 11 | 12 | AndroidX: 13 | 14 | ``` 15 | implementation 'com.nex3z:flow-layout:1.3.3' 16 | ``` 17 | 18 | AppCompact: 19 | 20 | ``` 21 | implementation 'com.nex3z:flow-layout:1.2.4' 22 | ``` 23 | 24 | 25 | ## Usage 26 | 27 | ```xml 28 | 35 | 36 | 40 | 41 | 45 | 46 | 47 | 48 | 49 | ``` 50 | 51 | 52 | ## Attributes 53 | 54 | | Attribute | Format | Description | 55 | |--------------------------|------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------| 56 | | flFlow | boolean | `true` to allow flow. `false` to restrict all child views in one row. The default is `true`. | 57 | | flChildSpacing | `auto`/dimension | The horizontal spacing between child views. Either `auto`, or a fixed size. The default is 0dp. | 58 | | flChildSpacingForLastRow | `auto`/`align`/
dimension | The horizontal spacing between child views of the last row. Either `auto`, `align` or a fixed size. If not set, `childSpacing` will be used instead. | 59 | | flRowSpacing | `auto`/dimension | The vertical spacing between rows. Either `auto`, or a fixed size. The default is 0dp. | 60 | | flRtl | boolean | `true` to layout child views from right to left. `false` to layout from left to right. The default is `false`. | 61 | | flMaxRows | integer | The maximum height of FlowLayout in terms of number of rows. | 62 | 63 | `auto` means that the actual spacing is calculated as per the size of the `FlowLayout` and the number of child views (or rows), so that the child views (or rows) are placed evenly. 64 | 65 | `align` in `childSpacingForLastRow` means that the horizontal spacing of the child views in the last row keeps the same with the spacing used in the row above. If there is only one row in `FlowLayout` and the `childSpacingForLastRow` is set to `align`, this value is ignored and the actual spacing is calculated using `childSpacing`. 66 | 67 | 68 | ## Licence 69 | 70 | ``` 71 | Copyright 2016 nex3z 72 | 73 | Licensed under the Apache License, Version 2.0 (the "License"); 74 | you may not use this file except in compliance with the License. 75 | You may obtain a copy of the License at 76 | 77 | http://www.apache.org/licenses/LICENSE-2.0 78 | 79 | Unless required by applicable law or agreed to in writing, software 80 | distributed under the License is distributed on an "AS IS" BASIS, 81 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 82 | See the License for the specific language governing permissions and 83 | limitations under the License. 84 | ``` 85 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | google() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:4.1.3' 10 | classpath 'com.vanniktech:gradle-maven-publish-plugin:0.13.0' 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | jcenter() 17 | google() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /flowlayout/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /flowlayout/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.vanniktech.maven.publish' 3 | 4 | android { 5 | compileSdkVersion 30 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 30 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | implementation fileTree(dir: 'libs', include: ['*.jar']) 26 | testImplementation 'junit:junit:4.12' 27 | androidTestImplementation 'androidx.test:runner:1.2.0' 28 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 29 | } 30 | -------------------------------------------------------------------------------- /flowlayout/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /flowlayout/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /flowlayout/src/main/java/com/nex3z/flowlayout/FlowAdapter.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout; 2 | 3 | import android.view.View; 4 | import android.view.ViewGroup; 5 | 6 | import java.lang.ref.WeakReference; 7 | 8 | public abstract class FlowAdapter { 9 | 10 | private WeakReference mFlowLayoutRef; 11 | 12 | public void setFlowLayout(FlowLayout layout) { 13 | mFlowLayoutRef = new WeakReference<>(layout); 14 | } 15 | 16 | public FlowLayout getFlowLayout() { 17 | return mFlowLayoutRef != null ? mFlowLayoutRef.get() : null; 18 | } 19 | 20 | public abstract int getItemCount(); 21 | 22 | public abstract VH createViewHolder(ViewGroup parent, int viewType); 23 | 24 | public abstract void bindView(VH view, int position); 25 | 26 | public int getItemViewType(int position) { 27 | return position; 28 | } 29 | 30 | public void notifyDataSetChanged() { 31 | FlowLayout layout = getFlowLayout(); 32 | if (layout != null) { 33 | layout.requestLayout(); 34 | } 35 | } 36 | 37 | public static class ViewHolder { 38 | public View itemView; 39 | 40 | public ViewHolder(View itemView) { 41 | this.itemView = itemView; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /flowlayout/src/main/java/com/nex3z/flowlayout/FlowLayout.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.util.AttributeSet; 6 | import android.util.TypedValue; 7 | import android.view.Gravity; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class FlowLayout extends ViewGroup { 15 | private static final String LOG_TAG = FlowLayout.class.getSimpleName(); 16 | 17 | /** 18 | * Special value for the child view spacing. 19 | * SPACING_AUTO means that the actual spacing is calculated according to the size of the 20 | * container and the number of the child views, so that the child views are placed evenly in 21 | * the container. 22 | */ 23 | public static final int SPACING_AUTO = -65536; 24 | 25 | /** 26 | * Special value for the horizontal spacing of the child views in the last row 27 | * SPACING_ALIGN means that the horizontal spacing of the child views in the last row keeps 28 | * the same with the spacing used in the row above. If there is only one row, this value is 29 | * ignored and the spacing will be calculated according to childSpacing. 30 | */ 31 | public static final int SPACING_ALIGN = -65537; 32 | 33 | private static final int SPACING_UNDEFINED = -65538; 34 | 35 | private static final int UNSPECIFIED_GRAVITY = -1; 36 | 37 | private static final int ROW_VERTICAL_GRAVITY_AUTO = -65536; 38 | 39 | private static final boolean DEFAULT_FLOW = true; 40 | private static final int DEFAULT_CHILD_SPACING = 0; 41 | private static final int DEFAULT_CHILD_SPACING_FOR_LAST_ROW = SPACING_UNDEFINED; 42 | private static final float DEFAULT_ROW_SPACING = 0; 43 | private static final boolean DEFAULT_RTL = false; 44 | private static final int DEFAULT_MAX_ROWS = Integer.MAX_VALUE; 45 | 46 | private boolean mFlow = DEFAULT_FLOW; 47 | private int mChildSpacing = DEFAULT_CHILD_SPACING; 48 | private int mMinChildSpacing = DEFAULT_CHILD_SPACING; 49 | private int mChildSpacingForLastRow = DEFAULT_CHILD_SPACING_FOR_LAST_ROW; 50 | private float mRowSpacing = DEFAULT_ROW_SPACING; 51 | private float mAdjustedRowSpacing = DEFAULT_ROW_SPACING; 52 | private boolean mRtl = DEFAULT_RTL; 53 | private int mMaxRows = DEFAULT_MAX_ROWS; 54 | private int mGravity = UNSPECIFIED_GRAVITY; 55 | private int mRowVerticalGravity = ROW_VERTICAL_GRAVITY_AUTO; 56 | private int mExactMeasuredHeight; 57 | 58 | private List mHorizontalSpacingForRow = new ArrayList<>(); 59 | private List mHeightForRow = new ArrayList<>(); 60 | private List mWidthForRow = new ArrayList<>(); 61 | private List mChildNumForRow = new ArrayList<>(); 62 | 63 | private FlowAdapter mAdapter; 64 | 65 | public FlowLayout(Context context) { 66 | this(context, null); 67 | } 68 | 69 | public FlowLayout(Context context, AttributeSet attrs) { 70 | super(context, attrs); 71 | 72 | TypedArray a = context.getTheme().obtainStyledAttributes( 73 | attrs, R.styleable.FlowLayout, 0, 0); 74 | try { 75 | mFlow = a.getBoolean(R.styleable.FlowLayout_flFlow, DEFAULT_FLOW); 76 | mChildSpacing = getDimensionOrInt(a, R.styleable.FlowLayout_flChildSpacing, (int) dpToPx(DEFAULT_CHILD_SPACING)); 77 | mMinChildSpacing = getDimensionOrInt(a, R.styleable.FlowLayout_flMinChildSpacing, (int) dpToPx(DEFAULT_CHILD_SPACING)); 78 | mChildSpacingForLastRow = getDimensionOrInt(a, R.styleable.FlowLayout_flChildSpacingForLastRow, SPACING_UNDEFINED); 79 | mRowSpacing = getDimensionOrInt(a, R.styleable.FlowLayout_flRowSpacing, (int) dpToPx(DEFAULT_ROW_SPACING)); 80 | mMaxRows = a.getInt(R.styleable.FlowLayout_flMaxRows, DEFAULT_MAX_ROWS); 81 | mRtl = a.getBoolean(R.styleable.FlowLayout_flRtl, DEFAULT_RTL); 82 | mGravity = a.getInt(R.styleable.FlowLayout_android_gravity, UNSPECIFIED_GRAVITY); 83 | mRowVerticalGravity = a.getInt(R.styleable.FlowLayout_flRowVerticalGravity, ROW_VERTICAL_GRAVITY_AUTO); 84 | } finally { 85 | a.recycle(); 86 | } 87 | } 88 | 89 | private int getDimensionOrInt(TypedArray a, int index, int defValue) { 90 | TypedValue tv = new TypedValue(); 91 | a.getValue(index, tv); 92 | if (tv.type == TypedValue.TYPE_DIMENSION) { 93 | return a.getDimensionPixelSize(index, defValue); 94 | } else { 95 | return a.getInt(index, defValue); 96 | } 97 | } 98 | 99 | @Override 100 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 101 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 102 | 103 | final int widthSize = MeasureSpec.getSize(widthMeasureSpec); 104 | final int widthMode = MeasureSpec.getMode(widthMeasureSpec); 105 | final int heightSize = MeasureSpec.getSize(heightMeasureSpec); 106 | final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 107 | 108 | mHorizontalSpacingForRow.clear(); 109 | mHeightForRow.clear(); 110 | mWidthForRow.clear(); 111 | mChildNumForRow.clear(); 112 | 113 | int measuredHeight = 0, measuredWidth = 0, childCount = getChildCount(); 114 | int rowWidth = 0, maxChildHeightInRow = 0, childNumInRow = 0; 115 | final int rowSize = widthSize - getPaddingLeft() - getPaddingRight(); 116 | int rowTotalChildWidth = 0; 117 | final boolean allowFlow = widthMode != MeasureSpec.UNSPECIFIED && mFlow; 118 | final int childSpacing = mChildSpacing == SPACING_AUTO && widthMode == MeasureSpec.UNSPECIFIED 119 | ? 0 : mChildSpacing; 120 | final float tmpSpacing = childSpacing == SPACING_AUTO ? mMinChildSpacing : childSpacing; 121 | 122 | for (int i = 0; i < childCount; i++) { 123 | View child = getChildAt(i); 124 | if (child.getVisibility() == GONE) { 125 | continue; 126 | } 127 | 128 | LayoutParams childParams = child.getLayoutParams(); 129 | int horizontalMargin = 0, verticalMargin = 0; 130 | if (childParams instanceof MarginLayoutParams) { 131 | measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, measuredHeight); 132 | MarginLayoutParams marginParams = (MarginLayoutParams) childParams; 133 | horizontalMargin = marginParams.leftMargin + marginParams.rightMargin; 134 | verticalMargin = marginParams.topMargin + marginParams.bottomMargin; 135 | } else { 136 | measureChild(child, widthMeasureSpec, heightMeasureSpec); 137 | } 138 | 139 | int childWidth = child.getMeasuredWidth() + horizontalMargin; 140 | int childHeight = child.getMeasuredHeight() + verticalMargin; 141 | if (allowFlow && rowWidth + childWidth > rowSize) { // Need flow to next row 142 | // Save parameters for current row 143 | mHorizontalSpacingForRow.add( 144 | getSpacingForRow(childSpacing, rowSize, rowTotalChildWidth, childNumInRow)); 145 | mChildNumForRow.add(childNumInRow); 146 | mHeightForRow.add(maxChildHeightInRow); 147 | mWidthForRow.add(rowWidth - (int) tmpSpacing); 148 | if (mHorizontalSpacingForRow.size() <= mMaxRows) { 149 | measuredHeight += maxChildHeightInRow; 150 | } 151 | measuredWidth = Math.max(measuredWidth, rowWidth); 152 | 153 | // Place the child view to next row 154 | childNumInRow = 1; 155 | rowWidth = childWidth + (int) tmpSpacing; 156 | rowTotalChildWidth = childWidth; 157 | maxChildHeightInRow = childHeight; 158 | } else { 159 | childNumInRow++; 160 | rowWidth += childWidth + tmpSpacing; 161 | rowTotalChildWidth += childWidth; 162 | maxChildHeightInRow = Math.max(maxChildHeightInRow, childHeight); 163 | } 164 | } 165 | 166 | // Measure remaining child views in the last row 167 | if (mChildSpacingForLastRow == SPACING_ALIGN) { 168 | // For SPACING_ALIGN, use the same spacing from the row above if there is more than one 169 | // row. 170 | if (mHorizontalSpacingForRow.size() >= 1) { 171 | mHorizontalSpacingForRow.add( 172 | mHorizontalSpacingForRow.get(mHorizontalSpacingForRow.size() - 1)); 173 | } else { 174 | mHorizontalSpacingForRow.add( 175 | getSpacingForRow(childSpacing, rowSize, rowTotalChildWidth, childNumInRow)); 176 | } 177 | } else if (mChildSpacingForLastRow != SPACING_UNDEFINED) { 178 | // For SPACING_AUTO and specific DP values, apply them to the spacing strategy. 179 | mHorizontalSpacingForRow.add( 180 | getSpacingForRow(mChildSpacingForLastRow, rowSize, rowTotalChildWidth, childNumInRow)); 181 | } else { 182 | // For SPACING_UNDEFINED, apply childSpacing to the spacing strategy for the last row. 183 | mHorizontalSpacingForRow.add( 184 | getSpacingForRow(childSpacing, rowSize, rowTotalChildWidth, childNumInRow)); 185 | } 186 | 187 | mChildNumForRow.add(childNumInRow); 188 | mHeightForRow.add(maxChildHeightInRow); 189 | mWidthForRow.add(rowWidth - (int) tmpSpacing); 190 | if (mHorizontalSpacingForRow.size() <= mMaxRows) { 191 | measuredHeight += maxChildHeightInRow; 192 | } 193 | measuredWidth = Math.max(measuredWidth, rowWidth); 194 | 195 | if (childSpacing == SPACING_AUTO) { 196 | measuredWidth = widthSize; 197 | } else if (widthMode == MeasureSpec.UNSPECIFIED) { 198 | measuredWidth = measuredWidth + getPaddingLeft() + getPaddingRight(); 199 | } else { 200 | measuredWidth = Math.min(measuredWidth + getPaddingLeft() + getPaddingRight(), widthSize); 201 | } 202 | 203 | measuredHeight += getPaddingTop() + getPaddingBottom(); 204 | int rowNum = Math.min(mHorizontalSpacingForRow.size(), mMaxRows); 205 | float rowSpacing = mRowSpacing == SPACING_AUTO && heightMode == MeasureSpec.UNSPECIFIED 206 | ? 0 : mRowSpacing; 207 | if (rowSpacing == SPACING_AUTO) { 208 | if (rowNum > 1) { 209 | mAdjustedRowSpacing = (heightSize - measuredHeight) / (rowNum - 1); 210 | } else { 211 | mAdjustedRowSpacing = 0; 212 | } 213 | measuredHeight = heightSize; 214 | } else { 215 | mAdjustedRowSpacing = rowSpacing; 216 | if (rowNum > 1) { 217 | measuredHeight = heightMode == MeasureSpec.UNSPECIFIED 218 | ? ((int) (measuredHeight + mAdjustedRowSpacing * (rowNum - 1))) 219 | : (Math.min((int) (measuredHeight + mAdjustedRowSpacing * (rowNum - 1)), 220 | heightSize)); 221 | } 222 | } 223 | 224 | mExactMeasuredHeight = measuredHeight; 225 | 226 | measuredWidth = widthMode == MeasureSpec.EXACTLY ? widthSize : measuredWidth; 227 | measuredHeight = heightMode == MeasureSpec.EXACTLY ? heightSize : measuredHeight; 228 | 229 | setMeasuredDimension(measuredWidth, measuredHeight); 230 | } 231 | 232 | @Override 233 | protected void onLayout(boolean changed, int l, int t, int r, int b) { 234 | final int paddingLeft = getPaddingLeft(), paddingRight = getPaddingRight(), 235 | paddingTop = getPaddingTop(), paddingBottom = getPaddingBottom(); 236 | 237 | int x = mRtl ? (getWidth() - paddingRight) : paddingLeft; 238 | int y = paddingTop; 239 | 240 | int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 241 | int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; 242 | 243 | switch (verticalGravity) { 244 | case Gravity.CENTER_VERTICAL: { 245 | int offset = (b - t - paddingTop - paddingBottom - mExactMeasuredHeight) / 2; 246 | y += offset; 247 | break; 248 | } 249 | case Gravity.BOTTOM: { 250 | int offset = b - t - paddingTop - paddingBottom - mExactMeasuredHeight; 251 | y += offset; 252 | break; 253 | } 254 | default: 255 | break; 256 | } 257 | 258 | int horizontalPadding = paddingLeft + paddingRight, layoutWidth = r - l; 259 | x += getHorizontalGravityOffsetForRow(horizontalGravity, layoutWidth, horizontalPadding, 0); 260 | 261 | int verticalRowGravity = mRowVerticalGravity & Gravity.VERTICAL_GRAVITY_MASK; 262 | 263 | int rowCount = mChildNumForRow.size(), childIdx = 0; 264 | for (int row = 0; row < Math.min(rowCount, mMaxRows); row++) { 265 | int childNum = mChildNumForRow.get(row); 266 | int rowHeight = mHeightForRow.get(row); 267 | float spacing = mHorizontalSpacingForRow.get(row); 268 | for (int i = 0; i < childNum && childIdx < getChildCount(); ) { 269 | View child = getChildAt(childIdx++); 270 | if (child.getVisibility() == GONE) { 271 | continue; 272 | } else { 273 | i++; 274 | } 275 | 276 | LayoutParams childParams = child.getLayoutParams(); 277 | int marginLeft = 0, marginTop = 0, marginBottom = 0, marginRight = 0; 278 | if (childParams instanceof MarginLayoutParams) { 279 | MarginLayoutParams marginParams = (MarginLayoutParams) childParams; 280 | marginLeft = marginParams.leftMargin; 281 | marginRight = marginParams.rightMargin; 282 | marginTop = marginParams.topMargin; 283 | marginBottom = marginParams.bottomMargin; 284 | } 285 | 286 | int childWidth = child.getMeasuredWidth(); 287 | int childHeight = child.getMeasuredHeight(); 288 | int tt = y + marginTop; 289 | if (verticalRowGravity == Gravity.BOTTOM) { 290 | tt = y + rowHeight - marginBottom - childHeight; 291 | } else if (verticalRowGravity == Gravity.CENTER_VERTICAL) { 292 | tt = y + marginTop + (rowHeight - marginTop - marginBottom - childHeight) / 2; 293 | } 294 | int bb = tt + childHeight; 295 | if (mRtl) { 296 | int l1 = x - marginRight - childWidth; 297 | int r1 = x - marginRight; 298 | child.layout(l1, tt, r1, bb); 299 | x -= childWidth + spacing + marginLeft + marginRight; 300 | } else { 301 | int l2 = x + marginLeft; 302 | int r2 = x + marginLeft + childWidth; 303 | child.layout(l2, tt, r2, bb); 304 | x += childWidth + spacing + marginLeft + marginRight; 305 | } 306 | } 307 | x = mRtl ? (getWidth() - paddingRight) : paddingLeft; 308 | x += getHorizontalGravityOffsetForRow( 309 | horizontalGravity, layoutWidth, horizontalPadding, row + 1); 310 | y += rowHeight + mAdjustedRowSpacing; 311 | } 312 | 313 | for (int i = childIdx; i < getChildCount(); i++) { 314 | View child = getChildAt(i); 315 | if (child.getVisibility() == GONE) { 316 | continue; 317 | } 318 | child.layout(0, 0, 0, 0); 319 | } 320 | } 321 | 322 | private int getHorizontalGravityOffsetForRow(int horizontalGravity, int parentWidth, int horizontalPadding, int row) { 323 | if (mChildSpacing == SPACING_AUTO || row >= mWidthForRow.size() 324 | || row >= mChildNumForRow.size() || mChildNumForRow.get(row) <= 0) { 325 | return 0; 326 | } 327 | 328 | int offset = 0; 329 | switch (horizontalGravity) { 330 | case Gravity.CENTER_HORIZONTAL: 331 | offset = (parentWidth - horizontalPadding - mWidthForRow.get(row)) / 2; 332 | break; 333 | case Gravity.RIGHT: 334 | offset = parentWidth - horizontalPadding - mWidthForRow.get(row); 335 | break; 336 | default: 337 | break; 338 | } 339 | return offset; 340 | } 341 | 342 | @Override 343 | protected LayoutParams generateLayoutParams(LayoutParams p) { 344 | return new MarginLayoutParams(p); 345 | } 346 | 347 | @Override 348 | public LayoutParams generateLayoutParams(AttributeSet attrs) { 349 | return new MarginLayoutParams(getContext(), attrs); 350 | } 351 | 352 | /** 353 | * Returns whether to allow child views flow to next row when there is no enough space. 354 | * 355 | * @return Whether to flow child views to next row when there is no enough space. 356 | */ 357 | public boolean isFlow() { 358 | return mFlow; 359 | } 360 | 361 | /** 362 | * Sets whether to allow child views flow to next row when there is no enough space. 363 | * 364 | * @param flow true to allow flow. false to restrict all child views in one row. 365 | */ 366 | public void setFlow(boolean flow) { 367 | mFlow = flow; 368 | requestLayout(); 369 | } 370 | 371 | /** 372 | * Returns the horizontal spacing between child views. 373 | * 374 | * @return The spacing, either {@link FlowLayout#SPACING_AUTO}, or a fixed size in pixels. 375 | */ 376 | public int getChildSpacing() { 377 | return mChildSpacing; 378 | } 379 | 380 | /** 381 | * Sets the horizontal spacing between child views. 382 | * 383 | * @param childSpacing The spacing, either {@link FlowLayout#SPACING_AUTO}, or a fixed size in 384 | * pixels. 385 | */ 386 | public void setChildSpacing(int childSpacing) { 387 | mChildSpacing = childSpacing; 388 | requestLayout(); 389 | } 390 | 391 | /** 392 | * Returns the horizontal spacing between child views of the last row. 393 | * 394 | * @return The spacing, either {@link FlowLayout#SPACING_AUTO}, 395 | * {@link FlowLayout#SPACING_ALIGN}, or a fixed size in pixels 396 | */ 397 | public int getChildSpacingForLastRow() { 398 | return mChildSpacingForLastRow; 399 | } 400 | 401 | /** 402 | * Sets the horizontal spacing between child views of the last row. 403 | * 404 | * @param childSpacingForLastRow The spacing, either {@link FlowLayout#SPACING_AUTO}, 405 | * {@link FlowLayout#SPACING_ALIGN}, or a fixed size in pixels 406 | */ 407 | public void setChildSpacingForLastRow(int childSpacingForLastRow) { 408 | mChildSpacingForLastRow = childSpacingForLastRow; 409 | requestLayout(); 410 | } 411 | 412 | /** 413 | * Returns the vertical spacing between rows. 414 | * 415 | * @return The spacing, either {@link FlowLayout#SPACING_AUTO}, or a fixed size in pixels. 416 | */ 417 | public float getRowSpacing() { 418 | return mRowSpacing; 419 | } 420 | 421 | /** 422 | * Sets the vertical spacing between rows in pixels. Use SPACING_AUTO to evenly place all rows 423 | * in vertical. 424 | * 425 | * @param rowSpacing The spacing, either {@link FlowLayout#SPACING_AUTO}, or a fixed size in 426 | * pixels. 427 | */ 428 | public void setRowSpacing(float rowSpacing) { 429 | mRowSpacing = rowSpacing; 430 | requestLayout(); 431 | } 432 | 433 | /** 434 | * Returns the maximum number of rows of the FlowLayout. 435 | * 436 | * @return The maximum number of rows. 437 | */ 438 | public int getMaxRows() { 439 | return mMaxRows; 440 | } 441 | 442 | /** 443 | * Sets the height of the FlowLayout to be at most maxRows tall. 444 | * 445 | * @param maxRows The maximum number of rows. 446 | */ 447 | public void setMaxRows(int maxRows) { 448 | mMaxRows = maxRows; 449 | requestLayout(); 450 | } 451 | 452 | public void setGravity(int gravity) { 453 | if (mGravity != gravity) { 454 | mGravity = gravity; 455 | requestLayout(); 456 | } 457 | } 458 | 459 | public void setRowVerticalGravity(int rowVerticalGravity) { 460 | if (mRowVerticalGravity != rowVerticalGravity) { 461 | mRowVerticalGravity = rowVerticalGravity; 462 | requestLayout(); 463 | } 464 | } 465 | 466 | public boolean isRtl() { 467 | return mRtl; 468 | } 469 | 470 | public void setRtl(boolean rtl) { 471 | mRtl = rtl; 472 | requestLayout(); 473 | } 474 | 475 | public int getMinChildSpacing() { 476 | return mMinChildSpacing; 477 | } 478 | 479 | public void setMinChildSpacing(int minChildSpacing) { 480 | this.mMinChildSpacing = minChildSpacing; 481 | requestLayout(); 482 | } 483 | 484 | public int getRowsCount() { 485 | return mChildNumForRow.size(); 486 | } 487 | 488 | private float getSpacingForRow(int spacingAttribute, int rowSize, int usedSize, int childNum) { 489 | float spacing; 490 | if (spacingAttribute == SPACING_AUTO) { 491 | if (childNum > 1) { 492 | spacing = (rowSize - usedSize) / (childNum - 1); 493 | } else { 494 | spacing = 0; 495 | } 496 | } else { 497 | spacing = spacingAttribute; 498 | } 499 | return spacing; 500 | } 501 | 502 | private float dpToPx(float dp) { 503 | return TypedValue.applyDimension( 504 | TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); 505 | } 506 | 507 | 508 | public void setAdapter(FlowAdapter adapter) { 509 | this.mAdapter = adapter; 510 | mAdapter.setFlowLayout(this); 511 | refreshViews(); 512 | } 513 | 514 | private void refreshViews() { 515 | removeAllViews(); 516 | if (mAdapter == null) return; 517 | 518 | final int count = mAdapter.getItemCount(); 519 | for (int i = 0; i < count; i++) { 520 | int viewType = mAdapter.getItemViewType(i); 521 | FlowAdapter.ViewHolder viewHolder = mAdapter.createViewHolder(this, viewType); 522 | mAdapter.bindView(viewHolder, i); 523 | addView(viewHolder.itemView); 524 | } 525 | } 526 | 527 | } 528 | -------------------------------------------------------------------------------- /flowlayout/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 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 | -------------------------------------------------------------------------------- /flowlayout/src/test/java/com/nex3z/flowlayout/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /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 | android.useAndroidX=true 19 | android.enableJetifier=true 20 | 21 | GROUP=com.nex3z 22 | POM_ARTIFACT_ID=flow-layout 23 | VERSION_NAME=1.3.4-beta01 24 | 25 | POM_NAME=FlowLayout 26 | POM_DESCRIPTION=A flow layout for Android with auto-spacing. 27 | POM_INCEPTION_YEAR=2016 28 | 29 | POM_URL=https://github.com/nex3z/FlowLayout 30 | POM_SCM_URL=https://github.com/nex3z/FlowLayout 31 | POM_SCM_CONNECTION=scm:git:git://github.com/nex3z/FlowLayout.git 32 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/nex3z/FlowLayout.git 33 | 34 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 35 | POM_LICENCE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt 36 | POM_LICENCE_DIST=repo 37 | 38 | POM_DEVELOPER_ID=nex3z 39 | POM_DEVELOPER_NAME=Tianxing Li 40 | POM_DEVELOPER_URL=https://github.com/nex3z 41 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nex3z/FlowLayout/cf44974fd72987bd73ea7315c30c26fb74608151/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Feb 08 09:55:39 CST 2021 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-6.5-bin.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 | -------------------------------------------------------------------------------- /images/sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nex3z/FlowLayout/cf44974fd72987bd73ea7315c30c26fb74608151/images/sample.png -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 30 5 | 6 | defaultConfig { 7 | applicationId "com.nex3z.flowlayout.sample" 8 | minSdkVersion 15 9 | targetSdkVersion 30 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | implementation fileTree(dir: 'libs', include: ['*.jar']) 24 | implementation project(path: ':flowlayout') 25 | implementation 'androidx.appcompat:appcompat:1.1.0' 26 | implementation 'androidx.recyclerview:recyclerview:1.1.0' 27 | 28 | testImplementation 'junit:junit:4.12' 29 | androidTestImplementation 'androidx.test:runner:1.2.0' 30 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 31 | } 32 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/nex3z/flowlayout/flowlayout/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout.flowlayout; 2 | 3 | import android.content.Context; 4 | import androidx.test.InstrumentationRegistry; 5 | import androidx.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.nex3z.flowlayout.flowlayout", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /sample/src/main/java/com/nex3z/flowlayout/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout.sample; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import androidx.appcompat.app.AppCompatActivity; 6 | import android.util.TypedValue; 7 | import android.view.View; 8 | import android.widget.Button; 9 | import android.widget.TextView; 10 | 11 | import com.nex3z.flowlayout.FlowLayout; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | public class MainActivity extends AppCompatActivity { 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(R.layout.activity_main); 22 | initButton(); 23 | 24 | fillAutoSpacingLayout(); 25 | } 26 | 27 | private void initButton() { 28 | Button btn = findViewById(R.id.btn_recyclerview); 29 | btn.setOnClickListener(new View.OnClickListener() { 30 | @Override 31 | public void onClick(View v) { 32 | Intent intent = new Intent(MainActivity.this, RecyclerViewActivity.class); 33 | startActivity(intent); 34 | } 35 | }); 36 | Button btnTestAdapter = findViewById(R.id.btn_test_adapter); 37 | btnTestAdapter.setOnClickListener(new View.OnClickListener() { 38 | @Override 39 | public void onClick(View view) { 40 | //测试 adapter 41 | FlowLayout flow2 = findViewById(R.id.flow2); 42 | List datas = new ArrayList<>(); 43 | datas.add("Java"); 44 | datas.add("C++"); 45 | datas.add("C#"); 46 | datas.add("Rust"); 47 | datas.add("Kotlin"); 48 | flow2.setAdapter(new SimpleFlowAdapter(datas)); 49 | } 50 | }); 51 | } 52 | 53 | private void fillAutoSpacingLayout() { 54 | FlowLayout flowLayout = findViewById(R.id.flow); 55 | String[] dummyTexts = getResources().getStringArray(R.array.lorem_ipsum); 56 | 57 | for (String text : dummyTexts) { 58 | TextView textView = buildLabel(text); 59 | flowLayout.addView(textView); 60 | } 61 | } 62 | 63 | private TextView buildLabel(String text) { 64 | TextView textView = new TextView(this); 65 | textView.setText(text); 66 | textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); 67 | textView.setPadding((int)dpToPx(16), (int)dpToPx(8), (int)dpToPx(16), (int)dpToPx(8)); 68 | textView.setBackgroundResource(R.drawable.label_bg); 69 | 70 | return textView; 71 | } 72 | 73 | private float dpToPx(float dp){ 74 | return TypedValue.applyDimension( 75 | TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /sample/src/main/java/com/nex3z/flowlayout/sample/RecyclerViewActivity.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout.sample; 2 | 3 | import android.os.Bundle; 4 | import androidx.appcompat.app.AppCompatActivity; 5 | import androidx.recyclerview.widget.LinearLayoutManager; 6 | import androidx.recyclerview.widget.RecyclerView; 7 | 8 | public class RecyclerViewActivity extends AppCompatActivity { 9 | 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.activity_recycler_view); 14 | 15 | initRecyclerView(); 16 | } 17 | 18 | private void initRecyclerView() { 19 | RecyclerView recyclerView = findViewById(R.id.rv_list); 20 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 21 | // recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); 22 | SimpleAdapter adapter = new SimpleAdapter(); 23 | recyclerView.setAdapter(adapter); 24 | adapter.setCount(10); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /sample/src/main/java/com/nex3z/flowlayout/sample/SimpleAdapter.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout.sample; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.annotation.NonNull; 6 | import androidx.recyclerview.widget.RecyclerView; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.TextView; 11 | 12 | public class SimpleAdapter extends RecyclerView.Adapter { 13 | 14 | private int mCount = 0; 15 | 16 | @NonNull 17 | @Override 18 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 19 | Context context = parent.getContext(); 20 | LayoutInflater inflater = LayoutInflater.from(context); 21 | 22 | View contactView = inflater.inflate(R.layout.item, parent, false); 23 | 24 | return new ViewHolder(contactView); 25 | } 26 | 27 | @Override 28 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) { 29 | holder.mTvCount.setText(String.valueOf(position)); 30 | } 31 | 32 | @Override 33 | public int getItemCount() { 34 | return mCount; 35 | } 36 | 37 | public void setCount(int count) { 38 | mCount = count; 39 | notifyDataSetChanged(); 40 | } 41 | 42 | public class ViewHolder extends RecyclerView.ViewHolder { 43 | TextView mTvCount; 44 | public ViewHolder(final View itemView) { 45 | super(itemView); 46 | mTvCount = itemView.findViewById(R.id.tv_count); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /sample/src/main/java/com/nex3z/flowlayout/sample/SimpleFlowAdapter.java: -------------------------------------------------------------------------------- 1 | package com.nex3z.flowlayout.sample; 2 | 3 | import android.view.View; 4 | import android.view.ViewGroup; 5 | import android.widget.TextView; 6 | 7 | import com.nex3z.flowlayout.FlowAdapter; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public class SimpleFlowAdapter extends FlowAdapter { 13 | public SimpleFlowAdapter(List datas) { 14 | this.datas = datas; 15 | } 16 | 17 | public void setDatas(List datas) { 18 | this.datas = datas; 19 | } 20 | 21 | private List datas = new ArrayList<>(); 22 | 23 | @Override 24 | public int getItemCount() { 25 | return datas.size(); 26 | } 27 | 28 | @Override 29 | public ViewHolder createViewHolder(ViewGroup parent, int viewType) { 30 | View view = View.inflate(parent.getContext(), R.layout.item_label, null); 31 | return new ViewHolder(view); 32 | } 33 | 34 | @Override 35 | public void bindView(ViewHolder viewHolder, int position) { 36 | viewHolder.tvTitle.setText(datas.get(position)); 37 | } 38 | 39 | 40 | class ViewHolder extends FlowAdapter.ViewHolder { 41 | TextView tvTitle; 42 | 43 | public ViewHolder(View itemView) { 44 | super(itemView); 45 | tvTitle = itemView.findViewById(R.id.tv_title); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /sample/src/main/res/drawable/box.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/label_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/label_bg2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 18 | 19 | 25 | 26 | 34 | 35 | 42 | 43 | 50 | 51 | 58 | 59 | 66 | 67 | 74 | 75 | 82 | 83 | 90 | 91 | 92 | 93 | 94 | 103 | 104 | 110 | 111 | 116 | 117 | 123 | 124 | 130 | 131 | 137 | 138 | 143 | 144 | 150 | 151 | 157 | 158 | 159 | 169 | 170 | 176 | 177 | 182 | 183 | 189 | 190 | 196 | 197 | 203 | 204 | 209 | 210 | 216 | 217 | 223 | 224 | 225 | 235 | 236 | 242 | 243 | 248 | 249 | 255 | 256 | 262 | 263 | 264 | 270 | 271 | 276 | 277 | 283 | 284 | 290 | 291 | 292 |