├── .github ├── dependabot.yaml └── workflows │ └── android.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── expandabletext ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── io │ └── dokar │ └── expandabletext │ └── ExpandableText.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images └── screen.gif ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── io │ │ └── dokar │ │ └── expandabletext │ │ └── sample │ │ ├── MainActivity.kt │ │ └── ui │ │ └── theme │ │ ├── Color.kt │ │ ├── Shape.kt │ │ ├── Theme.kt │ │ └── Type.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-mdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xxhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xxxhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ └── values │ ├── colors.xml │ ├── strings.xml │ └── themes.xml └── settings.gradle /.github/dependabot.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: "gradle" 5 | directory: "/" 6 | schedule: 7 | interval: "daily" 8 | 9 | - package-ecosystem: "github-actions" 10 | directory: "/" 11 | schedule: 12 | interval: "daily" -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | - name: set up JDK 17 17 | uses: actions/setup-java@v4 18 | with: 19 | java-version: '17' 20 | distribution: 'adopt' 21 | cache: gradle 22 | 23 | - name: Grant execute permission for gradlew 24 | run: chmod +x gradlew 25 | - name: Build with Gradle 26 | run: ./gradlew build 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | -------------------------------------------------------------------------------- /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 | # ExpandableText 2 | 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.dokar3/expandabletext/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.github.dokar3/expandabletext) 4 | 5 | Expandable text, similar to `Text()` in Jetpack Compose. 6 | 7 | [Sample](/sample/src/main/java/io/dokar/expandabletext/sample/MainActivity.kt) screen: 8 | 9 | ![Screen gif](/images/screen.gif) 10 | 11 | # Usage 12 | 13 | Add the dependency [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.dokar3/expandabletext/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.github.dokar3/expandabletext) : 14 | 15 | ```groovy 16 | implementation 'io.github.dokar3:expandabletext:latest_version' 17 | ``` 18 | 19 | Show some texts: 20 | 21 | ```kotlin 22 | val text = "Your long text ".repeat(10) 23 | var expanded by remember { mutableStateOf(false) } 24 | ExpandableText( 25 | expanded = expanded, 26 | text = text, 27 | collapsedMaxLines = 2, 28 | modifier = Modifier 29 | .animateContentSize() 30 | .clickable { expanded = !expanded }, 31 | toggle = { Text(text = if (expanded) "Show less" else "Show more") }, 32 | ) 33 | ``` 34 | 35 | # Known problems 36 | 37 | - `toggle` will not be visible if: 38 | - `overflow` was set to `TextOverflow.Ellipsis`: 39 | ```kotlin 40 | ExpandableText( 41 | // ... 42 | overflow = TextOverflow.Ellipsis, 43 | ) 44 | ``` 45 | - `text` is an `AnnoatedString` and a `ParagraphStyle` was applied to the line needed to show the toggle. For example: 46 | ```kotlin 47 | val text = buildAnnotatedString { 48 | withStyle(ParagraphStyle()) { 49 | append("Some long text...") 50 | } 51 | } 52 | ExpandableText( 53 | text = text, 54 | // ... 55 | ) 56 | ``` 57 | 58 | # License 59 | 60 | ``` 61 | Copyright 2022 dokar3 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | ``` 75 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | kotlin_versoin = '2.0.0' 4 | compose_bom_version = '2024.06.00' 5 | compile_sdk = 34 6 | target_sdk = 34 7 | } 8 | }// Top-level build file where you can add configuration options common to all sub-projects/modules. 9 | plugins { 10 | id 'org.jetbrains.kotlin.android' version "$kotlin_versoin" apply false 11 | id 'org.jetbrains.kotlin.plugin.compose' version "$kotlin_versoin" apply false 12 | id 'com.android.application' version '8.5.0' apply false 13 | id 'com.android.library' version '8.5.0' apply false 14 | id 'com.vanniktech.maven.publish' version '0.29.0' apply false 15 | } 16 | 17 | allprojects { 18 | plugins.withId("com.vanniktech.maven.publish") { 19 | mavenPublishing { 20 | publishToMavenCentral("S01") 21 | signAllPublications() 22 | } 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /expandabletext/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /expandabletext/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'org.jetbrains.kotlin.android' 4 | id 'com.vanniktech.maven.publish' 5 | id 'org.jetbrains.kotlin.plugin.compose' 6 | } 7 | 8 | android { 9 | namespace 'io.dokar.expandabletext' 10 | 11 | compileSdk compile_sdk 12 | 13 | defaultConfig { 14 | minSdk 21 15 | targetSdk target_sdk 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | consumerProguardFiles "consumer-rules.pro" 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | compileOptions { 28 | sourceCompatibility JavaVersion.VERSION_1_8 29 | targetCompatibility JavaVersion.VERSION_1_8 30 | } 31 | buildFeatures { 32 | compose true 33 | } 34 | kotlinOptions { 35 | jvmTarget = '1.8' 36 | } 37 | } 38 | 39 | dependencies { 40 | 41 | implementation platform("androidx.compose:compose-bom:$compose_bom_version") 42 | implementation "androidx.compose.ui:ui" 43 | implementation "androidx.compose.ui:ui-util" 44 | implementation "androidx.compose.material:material" 45 | testImplementation 'junit:junit:4.13.2' 46 | androidTestImplementation 'androidx.test.ext:junit:1.2.1' 47 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' 48 | } -------------------------------------------------------------------------------- /expandabletext/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/expandabletext/consumer-rules.pro -------------------------------------------------------------------------------- /expandabletext/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 -------------------------------------------------------------------------------- /expandabletext/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /expandabletext/src/main/java/io/dokar/expandabletext/ExpandableText.kt: -------------------------------------------------------------------------------- 1 | package io.dokar.expandabletext 2 | 3 | import androidx.compose.foundation.text.InlineTextContent 4 | import androidx.compose.foundation.text.appendInlineContent 5 | import androidx.compose.material.LocalTextStyle 6 | import androidx.compose.material.Text 7 | import androidx.compose.runtime.Composable 8 | import androidx.compose.runtime.LaunchedEffect 9 | import androidx.compose.runtime.getValue 10 | import androidx.compose.runtime.mutableStateOf 11 | import androidx.compose.runtime.remember 12 | import androidx.compose.runtime.setValue 13 | import androidx.compose.ui.Modifier 14 | import androidx.compose.ui.geometry.Offset 15 | import androidx.compose.ui.graphics.Color 16 | import androidx.compose.ui.layout.Layout 17 | import androidx.compose.ui.text.AnnotatedString 18 | import androidx.compose.ui.text.Placeholder 19 | import androidx.compose.ui.text.PlaceholderVerticalAlign 20 | import androidx.compose.ui.text.TextLayoutResult 21 | import androidx.compose.ui.text.TextStyle 22 | import androidx.compose.ui.text.buildAnnotatedString 23 | import androidx.compose.ui.text.font.FontFamily 24 | import androidx.compose.ui.text.font.FontStyle 25 | import androidx.compose.ui.text.font.FontWeight 26 | import androidx.compose.ui.text.style.ResolvedTextDirection 27 | import androidx.compose.ui.text.style.TextAlign 28 | import androidx.compose.ui.text.style.TextDecoration 29 | import androidx.compose.ui.text.style.TextOverflow 30 | import androidx.compose.ui.unit.TextUnit 31 | import androidx.compose.ui.unit.sp 32 | import androidx.compose.ui.util.fastForEach 33 | import androidx.compose.ui.util.fastMap 34 | import kotlin.math.max 35 | 36 | 37 | private const val INLINE_CONTENT_ID = "EXPANDABLE_TEXT_TOGGLE" 38 | 39 | private data class ToggleSize( 40 | val width: Int = 0, 41 | val widthSp: TextUnit = 0.sp, 42 | val height: Int = 0, 43 | val heightSp: TextUnit = 0.sp 44 | ) 45 | 46 | private data class ExpandableTextInfo( 47 | val visibleCharCount: Int, 48 | val shouldShowToggleContent: Boolean, 49 | ) 50 | 51 | /** 52 | * Display an expandable text, require `maxLines` to make text expandable. 53 | * 54 | * @param expanded Controls the expanded state of text. 55 | * @param text Text to display. 56 | * @param collapsedMaxLines The max lines when [expanded] is false. 57 | * @param expandedMaxLines The max lines when [expanded] is true. Defaults to [Int.MAX_VALUE]. 58 | * @param toggle The toggle displayed at end of the text if text can not be fully displayed. 59 | * @see [Text] 60 | */ 61 | @Composable 62 | fun ExpandableText( 63 | expanded: Boolean, 64 | text: String, 65 | collapsedMaxLines: Int, 66 | modifier: Modifier = Modifier, 67 | expandedMaxLines: Int = Int.MAX_VALUE, 68 | toggle: @Composable (() -> Unit)? = null, 69 | color: Color = Color.Unspecified, 70 | fontSize: TextUnit = TextUnit.Unspecified, 71 | fontStyle: FontStyle? = null, 72 | fontWeight: FontWeight? = null, 73 | fontFamily: FontFamily? = null, 74 | letterSpacing: TextUnit = TextUnit.Unspecified, 75 | textDecoration: TextDecoration? = null, 76 | textAlign: TextAlign? = null, 77 | lineHeight: TextUnit = TextUnit.Unspecified, 78 | overflow: TextOverflow = TextOverflow.Clip, 79 | softWrap: Boolean = true, 80 | inlineContent: Map = mapOf(), 81 | onTextLayout: (TextLayoutResult) -> Unit = {}, 82 | style: TextStyle = LocalTextStyle.current 83 | ) { 84 | val annotatedString = remember(text) { AnnotatedString(text) } 85 | ExpandableText( 86 | expanded = expanded, 87 | text = annotatedString, 88 | modifier = modifier, 89 | toggle = toggle, 90 | color = color, 91 | fontSize = fontSize, 92 | fontStyle = fontStyle, 93 | fontWeight = fontWeight, 94 | fontFamily = fontFamily, 95 | letterSpacing = letterSpacing, 96 | textDecoration = textDecoration, 97 | textAlign = textAlign, 98 | lineHeight = lineHeight, 99 | overflow = overflow, 100 | softWrap = softWrap, 101 | collapsedMaxLines = collapsedMaxLines, 102 | expandedMaxLines = expandedMaxLines, 103 | inlineContent = inlineContent, 104 | onTextLayout = onTextLayout, 105 | style = style 106 | ) 107 | } 108 | 109 | /** 110 | * Display an expandable text, require `maxLines` to make text expandable. 111 | * 112 | * @param expanded Controls the expanded state of text. 113 | * @param text Text to display. 114 | * @param collapsedMaxLines The max lines when [expanded] is false. 115 | * @param expandedMaxLines The max lines when [expanded] is true. Defaults to [Int.MAX_VALUE]. 116 | * @param toggle The toggle displayed at end of the text if text can not be fully displayed. 117 | * @see [Text] 118 | */ 119 | @Composable 120 | fun ExpandableText( 121 | expanded: Boolean, 122 | text: AnnotatedString, 123 | collapsedMaxLines: Int, 124 | modifier: Modifier = Modifier, 125 | expandedMaxLines: Int = Int.MAX_VALUE, 126 | toggle: @Composable (() -> Unit)? = null, 127 | color: Color = Color.Unspecified, 128 | fontSize: TextUnit = TextUnit.Unspecified, 129 | fontStyle: FontStyle? = null, 130 | fontWeight: FontWeight? = null, 131 | fontFamily: FontFamily? = null, 132 | letterSpacing: TextUnit = TextUnit.Unspecified, 133 | textDecoration: TextDecoration? = null, 134 | textAlign: TextAlign? = null, 135 | lineHeight: TextUnit = TextUnit.Unspecified, 136 | overflow: TextOverflow = TextOverflow.Clip, 137 | softWrap: Boolean = true, 138 | inlineContent: Map = mapOf(), 139 | onTextLayout: (TextLayoutResult) -> Unit = {}, 140 | style: TextStyle = LocalTextStyle.current 141 | ) { 142 | var textInfo by remember(text) { 143 | mutableStateOf( 144 | ExpandableTextInfo( 145 | visibleCharCount = text.length, 146 | shouldShowToggleContent = false, 147 | ) 148 | ) 149 | } 150 | 151 | val expandableText = remember(text, toggle as Any?, textInfo) { 152 | if (textInfo.shouldShowToggleContent && toggle != null) { 153 | buildAnnotatedString { 154 | append(text.subSequence(0, textInfo.visibleCharCount)) 155 | appendInlineContent(INLINE_CONTENT_ID) 156 | } 157 | } else { 158 | text 159 | } 160 | } 161 | 162 | val layoutResult = remember { mutableStateOf(null) } 163 | 164 | val toggleSize = measureToggle(toggle) 165 | 166 | val expandableInlineContent = remember( 167 | inlineContent, 168 | toggle as Any?, 169 | textInfo, 170 | toggleSize, 171 | ) { 172 | if (textInfo.shouldShowToggleContent && toggle != null) { 173 | val content = InlineTextContent( 174 | placeholder = Placeholder( 175 | width = toggleSize.widthSp, 176 | height = toggleSize.heightSp, 177 | placeholderVerticalAlign = PlaceholderVerticalAlign.Center, 178 | ), 179 | children = { toggle() } 180 | ) 181 | inlineContent + Pair(INLINE_CONTENT_ID, content) 182 | } else { 183 | inlineContent 184 | } 185 | } 186 | 187 | fun tryUpdateTextInfo( 188 | toggleSize: ToggleSize, 189 | layoutRet: TextLayoutResult, 190 | ) { 191 | if (toggleSize.width == 0) return 192 | val actualMaxLines = if (expanded) expandedMaxLines else collapsedMaxLines 193 | if (layoutRet.lineCount == actualMaxLines) { 194 | val lineEnd = layoutRet.getLineEnd(layoutRet.lineCount - 1) 195 | if (lineEnd == expandableText.length) { 196 | // Text is fully displayed 197 | val visibleChars = if (textInfo.shouldShowToggleContent) { 198 | expandableText.length - 1 199 | } else { 200 | expandableText.length 201 | } 202 | textInfo = textInfo.copy(visibleCharCount = visibleChars) 203 | return 204 | } 205 | val lineTop = layoutRet.getLineTop(layoutRet.lineCount - 1) 206 | val isLtr = try { 207 | layoutRet.getParagraphDirection(lineEnd) == ResolvedTextDirection.Ltr 208 | } catch (e: ArrayIndexOutOfBoundsException) { 209 | // Error occurred in MultiParagraph.getParagraphDirection() 210 | true 211 | } 212 | val visibleChars = if (isLtr) { 213 | val toggleTopLeft = Offset( 214 | x = layoutRet.size.width - toggleSize.width.toFloat(), 215 | y = lineTop + toggleSize.height / 2f, 216 | ) 217 | var count = layoutRet.getOffsetForPosition(toggleTopLeft) 218 | while (count > 0) { 219 | val charRight = layoutRet.getBoundingBox(offset = count - 1).right 220 | val isOverlapped = charRight >= toggleTopLeft.x 221 | val isWhitespace = text[count - 1].isWhitespace() 222 | if (isOverlapped || isWhitespace) { 223 | count-- 224 | } else { 225 | break 226 | } 227 | } 228 | count 229 | } else { 230 | val toggleTopRight = Offset( 231 | x = toggleSize.width.toFloat(), 232 | y = lineTop + toggleSize.height / 2f, 233 | ) 234 | var count = layoutRet.getOffsetForPosition(toggleTopRight) 235 | while (count > 0) { 236 | val charLeft = layoutRet.getBoundingBox(offset = count - 1).left 237 | val isOverlapped = charLeft <= toggleTopRight.x 238 | val isWhitespace = text[count - 1].isWhitespace() 239 | if (isOverlapped || isWhitespace) { 240 | count-- 241 | } else { 242 | break 243 | } 244 | } 245 | count 246 | } 247 | textInfo = textInfo.copy( 248 | visibleCharCount = visibleChars, 249 | shouldShowToggleContent = true, 250 | ) 251 | } else { 252 | textInfo = textInfo.copy(visibleCharCount = text.length) 253 | } 254 | } 255 | 256 | LaunchedEffect( 257 | expanded, 258 | collapsedMaxLines, 259 | expandedMaxLines, 260 | toggleSize, 261 | layoutResult.value, 262 | ) { 263 | val layoutRet = layoutResult.value ?: return@LaunchedEffect 264 | if (toggleSize.width > 0) { 265 | tryUpdateTextInfo(toggleSize, layoutRet) 266 | } 267 | } 268 | 269 | Text( 270 | text = expandableText, 271 | modifier = modifier, 272 | color = color, 273 | fontSize = fontSize, 274 | fontStyle = fontStyle, 275 | fontWeight = fontWeight, 276 | fontFamily = fontFamily, 277 | letterSpacing = letterSpacing, 278 | textDecoration = textDecoration, 279 | textAlign = textAlign, 280 | lineHeight = lineHeight, 281 | overflow = overflow, 282 | softWrap = softWrap, 283 | maxLines = if (expanded) expandedMaxLines else collapsedMaxLines, 284 | inlineContent = expandableInlineContent, 285 | onTextLayout = { 286 | onTextLayout(it) 287 | layoutResult.value = it 288 | }, 289 | style = style 290 | ) 291 | } 292 | 293 | @Composable 294 | private fun measureToggle( 295 | content: @Composable (() -> Unit)?, 296 | ): ToggleSize { 297 | var size by remember(content as Any?) { mutableStateOf(ToggleSize()) } 298 | if (content != null) { 299 | Layout(content = content) { measurables, constraints -> 300 | var maxWidth = 0 301 | var maxHeight = 0 302 | measurables 303 | .fastMap { it.measure(constraints) } 304 | .fastForEach { 305 | maxWidth = max(maxWidth, it.measuredWidth) 306 | maxHeight = max(maxHeight, it.measuredHeight) 307 | } 308 | size = ToggleSize( 309 | width = maxWidth, 310 | widthSp = maxWidth.toSp(), 311 | height = maxHeight, 312 | heightSp = maxHeight.toSp(), 313 | ) 314 | layout(0, 0) {} 315 | } 316 | } 317 | return size 318 | } 319 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true 24 | 25 | GROUP=io.github.dokar3 26 | POM_ARTIFACT_ID=expandabletext 27 | VERSION_NAME=0.4.0 28 | 29 | POM_NAME=ExpandableText 30 | POM_DESCRIPTION=Expandable text for Jetpack Compose. 31 | POM_INCEPTION_YEAR=2022 32 | POM_URL=https://github.com/dokar3/ExpandableText 33 | 34 | POM_LICENSE_NAME=The Apache Software License, Version 2.0 35 | POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt 36 | POM_LICENSE_DIST=repo 37 | 38 | POM_SCM_URL=https://github.com/dokar3/ExpandableText 39 | POM_SCM_CONNECTION=scm:git:git://github.com/dokar3/ExpandableText.git 40 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/dokar3/ExpandableText.git 41 | 42 | POM_DEVELOPER_ID=dokar3 43 | POM_DEVELOPER_NAME=Dokar 44 | POM_DEVELOPER_URL=https://github.com/dokar3/ 45 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Feb 27 17:52:16 CST 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /images/screen.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/images/screen.gif -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'org.jetbrains.kotlin.android' 4 | id 'org.jetbrains.kotlin.plugin.compose' 5 | } 6 | 7 | android { 8 | namespace 'io.dokar.expandabletext.sample' 9 | 10 | compileSdk compile_sdk 11 | 12 | defaultConfig { 13 | applicationId "io.dokar.expandabletext.sample" 14 | minSdk 21 15 | targetSdk target_sdk 16 | versionCode 1 17 | versionName "1.0" 18 | 19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 20 | vectorDrawables { 21 | useSupportLibrary true 22 | } 23 | } 24 | 25 | buildTypes { 26 | release { 27 | minifyEnabled false 28 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 29 | } 30 | } 31 | compileOptions { 32 | sourceCompatibility JavaVersion.VERSION_1_8 33 | targetCompatibility JavaVersion.VERSION_1_8 34 | } 35 | kotlinOptions { 36 | jvmTarget = '1.8' 37 | } 38 | buildFeatures { 39 | compose true 40 | } 41 | packagingOptions { 42 | resources { 43 | excludes += '/META-INF/{AL2.0,LGPL2.1}' 44 | } 45 | } 46 | } 47 | 48 | dependencies { 49 | 50 | implementation project(':expandabletext') 51 | implementation 'androidx.core:core-ktx:1.13.1' 52 | 53 | implementation platform("androidx.compose:compose-bom:$compose_bom_version") 54 | implementation "androidx.compose.ui:ui" 55 | implementation "androidx.compose.material:material" 56 | implementation "androidx.compose.ui:ui-tooling-preview" 57 | 58 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.8.3' 59 | implementation 'androidx.activity:activity-compose:1.9.0' 60 | testImplementation 'junit:junit:4.13.2' 61 | androidTestImplementation 'androidx.test.ext:junit:1.2.1' 62 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' 63 | 64 | androidTestImplementation platform("androidx.compose:compose-bom:$compose_bom_version") 65 | androidTestImplementation "androidx.compose.ui:ui-test-junit4" 66 | debugImplementation "androidx.compose.ui:ui-tooling" 67 | } -------------------------------------------------------------------------------- /sample/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 -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/java/io/dokar/expandabletext/sample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package io.dokar.expandabletext.sample 2 | 3 | import android.os.Build 4 | import android.os.Bundle 5 | import android.view.View 6 | import androidx.activity.ComponentActivity 7 | import androidx.activity.compose.setContent 8 | import androidx.compose.animation.animateContentSize 9 | import androidx.compose.foundation.clickable 10 | import androidx.compose.foundation.interaction.MutableInteractionSource 11 | import androidx.compose.foundation.layout.Column 12 | import androidx.compose.foundation.layout.Spacer 13 | import androidx.compose.foundation.layout.fillMaxSize 14 | import androidx.compose.foundation.layout.height 15 | import androidx.compose.foundation.layout.padding 16 | import androidx.compose.foundation.rememberScrollState 17 | import androidx.compose.foundation.verticalScroll 18 | import androidx.compose.material.Icon 19 | import androidx.compose.material.MaterialTheme 20 | import androidx.compose.material.Surface 21 | import androidx.compose.material.Text 22 | import androidx.compose.material.icons.Icons 23 | import androidx.compose.material.icons.filled.KeyboardArrowDown 24 | import androidx.compose.material.icons.filled.KeyboardArrowUp 25 | import androidx.compose.runtime.Composable 26 | import androidx.compose.runtime.CompositionLocalProvider 27 | import androidx.compose.runtime.LaunchedEffect 28 | import androidx.compose.runtime.getValue 29 | import androidx.compose.runtime.mutableStateOf 30 | import androidx.compose.runtime.remember 31 | import androidx.compose.runtime.setValue 32 | import androidx.compose.ui.Modifier 33 | import androidx.compose.ui.graphics.toArgb 34 | import androidx.compose.ui.platform.LocalLayoutDirection 35 | import androidx.compose.ui.text.font.FontWeight 36 | import androidx.compose.ui.tooling.preview.datasource.LoremIpsum 37 | import androidx.compose.ui.unit.LayoutDirection 38 | import androidx.compose.ui.unit.dp 39 | import androidx.compose.ui.unit.sp 40 | import io.dokar.expandabletext.ExpandableText 41 | import io.dokar.expandabletext.sample.ui.theme.ExpandableTextTheme 42 | 43 | class MainActivity : ComponentActivity() { 44 | @Suppress("deprecation") 45 | override fun onCreate(savedInstanceState: Bundle?) { 46 | super.onCreate(savedInstanceState) 47 | 48 | setContent { 49 | val backgroundColor = MaterialTheme.colors.background 50 | LaunchedEffect(backgroundColor) { 51 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 52 | val flags = window.decorView.systemUiVisibility 53 | window.decorView.systemUiVisibility = flags or 54 | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 55 | window.statusBarColor = backgroundColor.toArgb() 56 | } 57 | } 58 | ExpandableTextTheme { 59 | // A surface container using the 'background' color from the theme 60 | Surface( 61 | modifier = Modifier.fillMaxSize(), 62 | color = MaterialTheme.colors.background 63 | ) { 64 | Example() 65 | } 66 | } 67 | } 68 | } 69 | } 70 | 71 | @Composable 72 | fun Example() { 73 | Column( 74 | modifier = Modifier 75 | .padding(16.dp) 76 | .verticalScroll(state = rememberScrollState()) 77 | ) { 78 | Text("\uD83D\uDCDC ExpandableText", fontSize = 22.sp, fontWeight = FontWeight.Bold) 79 | 80 | Spacer(modifier = Modifier.height(16.dp)) 81 | 82 | val text = "Very short text" 83 | Header("Not expandable (maxLines = ${text.length})") 84 | ExpandableText(expanded = false, text = text, collapsedMaxLines = text.length) 85 | 86 | Spacer(modifier = Modifier.height(16.dp)) 87 | 88 | Header("No toggle") 89 | ShowMoreText() 90 | 91 | Spacer(modifier = Modifier.height(16.dp)) 92 | 93 | Header("Text() toggle") 94 | ShowMoreText( 95 | toggle = { expanded -> 96 | Text( 97 | text = if (expanded) "Show less" else "Show more", 98 | color = MaterialTheme.colors.primary, 99 | ) 100 | } 101 | ) 102 | 103 | Spacer(modifier = Modifier.height(16.dp)) 104 | 105 | Header("Icon() toggle") 106 | ShowMoreText( 107 | toggle = { expanded -> 108 | Icon( 109 | imageVector = if (expanded) { 110 | Icons.Default.KeyboardArrowUp 111 | } else { 112 | Icons.Default.KeyboardArrowDown 113 | }, 114 | contentDescription = null, 115 | tint = MaterialTheme.colors.primary, 116 | ) 117 | } 118 | ) 119 | 120 | Spacer(modifier = Modifier.height(16.dp)) 121 | 122 | Header("Right-to-left") 123 | CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { 124 | ShowMoreText( 125 | text = LoremIpsumArabic, 126 | toggle = { expanded -> 127 | Text( 128 | text = if (expanded) "Show less" else "Show more", 129 | color = MaterialTheme.colors.primary, 130 | ) 131 | } 132 | ) 133 | } 134 | } 135 | } 136 | 137 | @Composable 138 | fun Header(text: String) { 139 | Text( 140 | text = text, 141 | color = MaterialTheme.colors.primary, 142 | fontSize = 18.sp, 143 | fontWeight = FontWeight.Bold, 144 | ) 145 | } 146 | 147 | @Composable 148 | fun ShowMoreText( 149 | modifier: Modifier = Modifier, 150 | text: String = LoremIpsum(words = 100).values.first(), 151 | toggle: @Composable ((expanded: Boolean) -> Unit)? = null, 152 | ) { 153 | var expanded by remember { mutableStateOf(false) } 154 | ExpandableText( 155 | expanded = expanded, 156 | text = text, 157 | collapsedMaxLines = 3, 158 | modifier = modifier 159 | .animateContentSize() 160 | .clickable( 161 | interactionSource = remember { MutableInteractionSource() }, 162 | indication = null, 163 | onClick = { expanded = !expanded } 164 | ), 165 | toggle = { 166 | if (toggle != null) { 167 | toggle(expanded) 168 | } 169 | }, 170 | ) 171 | } 172 | 173 | // Text copied from https://istizada.com/arabic-lorem-ipsum/ 174 | private const val LoremIpsumArabic = 175 | """لكن لا بد أن أوضح لك أن كل هذه الأفكار المغلوطة حول استنكار النشوة وتمجيد الألم نشأت بالفعل، وسأعرض لك التفاصيل لتكتشف حقيقة وأساس تلك السعادة البشرية، فلا أحد يرفض أو يكره أو يتجنب الشعور بالسعادة، ولكن بفضل هؤلاء الأشخاص الذين لا يدركون بأن السعادة لا بد أن نستشعرها بصورة أكثر عقلانية ومنطقية فيعرضهم هذا لمواجهة الظروف الأليمة، وأكرر بأنه لا يوجد من يرغب في الحب ونيل المنال ويتلذذ بالآلام، الألم هو الألم ولكن نتيجة لظروف ما قد تكمن السعاده فيما نتحمله من كد وأسي. 176 | و سأعرض مثال حي لهذا، من منا لم يتحمل جهد بدني شاق إلا من أجل الحصول على ميزة أو فائدة؟ ولكن من لديه الحق أن ينتقد شخص ما أراد أن يشعر بالسعادة التي لا تشوبها عواقب أليمة أو آخر أراد أن يتجنب الألم الذي ربما تنجم عنه بعض المتعة ؟ 177 | علي الجانب الآخر نشجب ونستنكر هؤلاء الرجال المفتونون بنشوة اللحظة الهائمون في رغباتهم فلا يدركون ما يعقبها من الألم والأسي المحتم، واللوم كذلك يشمل هؤلاء الذين أخفقوا في واجباتهم نتيجة لضعف إرادتهم فيتساوي مع هؤلاء الذين يتجنبون وينأون عن تحمل الكدح والألم .""" 178 | -------------------------------------------------------------------------------- /sample/src/main/java/io/dokar/expandabletext/sample/ui/theme/Color.kt: -------------------------------------------------------------------------------- 1 | package io.dokar.expandabletext.sample.ui.theme 2 | 3 | import androidx.compose.ui.graphics.Color 4 | 5 | val Purple200 = Color(0xFFBB86FC) 6 | val Purple500 = Color(0xFF6200EE) 7 | val Purple700 = Color(0xFF3700B3) 8 | val Teal200 = Color(0xFF03DAC5) -------------------------------------------------------------------------------- /sample/src/main/java/io/dokar/expandabletext/sample/ui/theme/Shape.kt: -------------------------------------------------------------------------------- 1 | package io.dokar.expandabletext.sample.ui.theme 2 | 3 | import androidx.compose.foundation.shape.RoundedCornerShape 4 | import androidx.compose.material.Shapes 5 | import androidx.compose.ui.unit.dp 6 | 7 | val Shapes = Shapes( 8 | small = RoundedCornerShape(4.dp), 9 | medium = RoundedCornerShape(4.dp), 10 | large = RoundedCornerShape(0.dp) 11 | ) -------------------------------------------------------------------------------- /sample/src/main/java/io/dokar/expandabletext/sample/ui/theme/Theme.kt: -------------------------------------------------------------------------------- 1 | package io.dokar.expandabletext.sample.ui.theme 2 | 3 | import androidx.compose.foundation.isSystemInDarkTheme 4 | import androidx.compose.material.MaterialTheme 5 | import androidx.compose.material.darkColors 6 | import androidx.compose.material.lightColors 7 | import androidx.compose.runtime.Composable 8 | 9 | private val DarkColorPalette = darkColors( 10 | primary = Purple200, 11 | primaryVariant = Purple700, 12 | secondary = Teal200 13 | ) 14 | 15 | private val LightColorPalette = lightColors( 16 | primary = Purple500, 17 | primaryVariant = Purple700, 18 | secondary = Teal200 19 | 20 | /* Other default colors to override 21 | background = Color.White, 22 | surface = Color.White, 23 | onPrimary = Color.White, 24 | onSecondary = Color.Black, 25 | onBackground = Color.Black, 26 | onSurface = Color.Black, 27 | */ 28 | ) 29 | 30 | @Composable 31 | fun ExpandableTextTheme( 32 | darkTheme: Boolean = isSystemInDarkTheme(), 33 | content: @Composable () -> Unit 34 | ) { 35 | val colors = if (darkTheme) { 36 | DarkColorPalette 37 | } else { 38 | LightColorPalette 39 | } 40 | 41 | MaterialTheme( 42 | colors = colors, 43 | typography = Typography, 44 | shapes = Shapes, 45 | content = content 46 | ) 47 | } -------------------------------------------------------------------------------- /sample/src/main/java/io/dokar/expandabletext/sample/ui/theme/Type.kt: -------------------------------------------------------------------------------- 1 | package io.dokar.expandabletext.sample.ui.theme 2 | 3 | import androidx.compose.material.Typography 4 | import androidx.compose.ui.text.TextStyle 5 | import androidx.compose.ui.text.font.FontFamily 6 | import androidx.compose.ui.text.font.FontWeight 7 | import androidx.compose.ui.unit.sp 8 | 9 | // Set of Material typography styles to start with 10 | val Typography = Typography( 11 | body1 = TextStyle( 12 | fontFamily = FontFamily.Default, 13 | fontWeight = FontWeight.Normal, 14 | fontSize = 16.sp 15 | ) 16 | /* Other default text styles to override 17 | button = TextStyle( 18 | fontFamily = FontFamily.Default, 19 | fontWeight = FontWeight.W500, 20 | fontSize = 14.sp 21 | ), 22 | caption = TextStyle( 23 | fontFamily = FontFamily.Default, 24 | fontWeight = FontWeight.Normal, 25 | fontSize = 12.sp 26 | ) 27 | */ 28 | ) -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /sample/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 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dokar3/ExpandableText/cb5fe7a983eff65669d322b4632ad26f0c2abb8b/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ExpandableText 3 | -------------------------------------------------------------------------------- /sample/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | google() 5 | mavenCentral() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | rootProject.name = "ExpandableText" 16 | include ':sample' 17 | include ':expandabletext' 18 | --------------------------------------------------------------------------------