├── .gitignore
├── Jenkinsfile
├── LICENSE.md
├── README.md
├── build.gradle
├── common
├── res
│ ├── font
│ │ ├── audiowide.xml
│ │ └── pacifico.xml
│ └── values
│ │ ├── font_certs.xml
│ │ ├── preloaded_fonts.xml
│ │ └── strings.xml
├── test
│ └── java
│ │ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ └── app
│ │ ├── MainActivityTest.kt
│ │ └── SpanMatcher.kt
├── testCommonx
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto.app
│ │ │ ├── AndroidXSpanMatcher.kt
│ │ │ └── ShadowResourcesCompat.java
│ └── resources
│ │ └── robolectric.properties
└── testSupport
│ ├── java
│ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ └── app
│ │ ├── ShadowResourcesCompat.java
│ │ └── SupportSpanMatcher.kt
│ └── resources
│ └── robolectric.properties
├── dependencies.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── images
├── bold_underline.png
├── disable_example.png
├── downloadable_fonts.png
├── edit_example.png
└── simple_example.png
├── javaApp
├── .gitignore
├── build.gradle
├── lint.xml
├── proguard-rules.pro
└── src
│ ├── androidx
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ └── app
│ │ │ └── MainActivity.java
│ └── res
│ │ └── layout
│ │ └── activity_main.xml
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ └── app
│ │ │ └── JavaApplication.java
│ └── 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.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ ├── material
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ └── app
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ └── values
│ │ └── styles.xml
│ └── support
│ ├── java
│ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ └── app
│ │ └── MainActivity.java
│ └── res
│ └── layout
│ └── activity_main.xml
├── kotlinApp
├── .gitignore
├── build.gradle
├── lint.xml
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ ├── MainActivityScreen.kt
│ │ └── MainActivityTest.kt
│ ├── androidx
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ └── app
│ │ │ └── MainActivity.kt
│ └── res
│ │ └── layout
│ │ └── activity_main.xml
│ ├── main
│ ├── AndroidManifest.xml
│ ├── ic_launcher-web.png
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ └── app
│ │ │ └── KotlinApplication.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.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ ├── material
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ └── app
│ │ │ └── MainActivity.kt
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ └── values
│ │ └── styles.xml
│ └── support
│ ├── java
│ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ └── app
│ │ └── MainActivity.kt
│ └── res
│ └── layout
│ └── activity_main.xml
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidx
│ └── java
│ │ └── androidx
│ │ └── appcompat
│ │ └── app
│ │ └── RialtoViewInflater.kt
│ ├── commonx
│ └── java
│ │ ├── androidx
│ │ └── appcompat
│ │ │ └── app
│ │ │ └── ViewFactory.kt
│ │ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ ├── RialtoDelegateImpl.kt
│ │ ├── androidx
│ │ └── widget
│ │ │ ├── RialtoEditText.kt
│ │ │ └── RialtoTextView.kt
│ │ ├── app
│ │ └── RialtoActivity.kt
│ │ └── font
│ │ └── FontRegistrar.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── stylingandroid
│ │ │ └── rialto
│ │ │ ├── Registry.kt
│ │ │ ├── RialtoBaseDelegate.kt
│ │ │ ├── RialtoDelegate.kt
│ │ │ ├── RialtoFactoryContext.kt
│ │ │ ├── RialtoRegistry.kt
│ │ │ ├── RialtoTextDelegate.kt
│ │ │ ├── TextViewDelegate.kt
│ │ │ ├── app
│ │ │ └── RialtoApplication.kt
│ │ │ ├── font
│ │ │ └── CustomTypefaceSpan.kt
│ │ │ └── format
│ │ │ └── SpannableFormatter.kt
│ └── res
│ │ └── values
│ │ ├── attrs.xml
│ │ └── strings.xml
│ ├── material
│ └── java
│ │ ├── androidx
│ │ └── appcompat
│ │ │ └── app
│ │ │ └── RialtoViewInflater.kt
│ │ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ └── material
│ │ └── widget
│ │ └── RialtoTextInputEditText.kt
│ ├── support
│ └── java
│ │ ├── android
│ │ └── support
│ │ │ └── v7
│ │ │ └── app
│ │ │ ├── RialtoViewInflater.kt
│ │ │ └── ViewFactory.kt
│ │ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ ├── RialtoDelegateImpl.kt
│ │ ├── app
│ │ └── RialtoActivity.kt
│ │ ├── font
│ │ └── FontRegistrar.kt
│ │ └── support
│ │ └── widget
│ │ ├── RialtoEditText.kt
│ │ └── RialtoTextView.kt
│ └── test
│ ├── java
│ └── com
│ │ └── stylingandroid
│ │ └── rialto
│ │ ├── RegistryTest.kt
│ │ ├── RialtoFactoryTest.kt
│ │ └── format
│ │ ├── FormatterRegexTest.kt
│ │ └── SpannableFormatterTest.kt
│ └── resources
│ └── mockito-extensions
│ └── org.mockito.plugins.MockMaker
├── publish.gradle
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | **/*.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | **/build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/Jenkinsfile:
--------------------------------------------------------------------------------
1 | node {
2 | stage('Checkout') {
3 | checkout scm
4 | }
5 |
6 | stage('Build') {
7 | sh "./gradlew clean assemble"
8 | }
9 |
10 | stage('Test') {
11 | sh "./gradlew test"
12 | }
13 |
14 | stage('Check') {
15 | sh "./gradlew check"
16 | }
17 |
18 | stage('Detekt') {
19 | sh "./gradlew detekt"
20 | }
21 |
22 | stage('Report') {
23 | androidLint canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '**/lint-results.xml', unHealthy: '', unstableTotalAll: '0'
24 | step([$class: 'CheckStylePublisher', canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '**/reports/**/detekt.xml', unHealthy: '', unstableTotalAll: '0'])
25 | junit '**/test-results/*Debug*/*.xml'
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
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 2018 Mark Allison
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 | [  ](https://bintray.com/stylingandroid/rialto/library/_latestVersion)
2 |
3 | ### Rialto
4 |
5 | _Rialto_ is an Android text styling library based upon Annotation Spans. Rialto enables you to provide consistent text
6 | formatting throughout your app by using annotations in your string resources.
7 |
8 | * [Getting Started](#getting-started)
9 | * [Combining Spans](#combining-spans)
10 | * [Cascading Registry](#cascading-registry)
11 | * [Format Strings](#format-strings)
12 | * [Downloadable Fonts](#downloadable-fonts)
13 | * [Java Interoperability](#java-interoperability)
14 | * [Internals](#internals)
15 |
16 | #### Getting Started
17 |
18 | To use Rialto you need to do two things: Firstly you need to initialise the Rialto framework and register the Spans which will get applied for specific key / value pairs in your annotations; Secondly you need to add annotations to your string resources using those key / value pairs and Rialto will do the rest.
19 |
20 | Rialto comes in three flavours depending on whether you're using the legacy Support AppCompat library, AndroidX AppCompat library, or Material components library. It does not currently support apps which use legacy framework themes as it is assumed that most modern apps or using either AppCompat or Material components (which currently depends on AndroidX AppCompat). In this example, we will look at how to use the AndroidX AppCompat version, but there are also examples of using the other flavours in the sample projects within the GitHub repo.
21 |
22 | Rialto is published to JCenter, so if you haven't already gort the JCenter repo configured in your build script, then you'll need to add it:
23 |
24 | ```groovy
25 | buildscript {
26 | repositories {
27 | ...
28 | jcenter()
29 | }
30 | }
31 | ```
32 |
33 | The first thing to do is to add the necessary dependency to your project:
34 |
35 | ```groovy
36 | dependencies {
37 | ...
38 | implementation 'com.stylingandroid.rialto:rialto-androidx:1.2.0'
39 | ...
40 | }
41 | ```
42 |
43 | If you are using the legacy AppCompat library use the artifact named rialto-support
instead; alternatively, if you're using the Material components library use rialto-material
.
44 |
45 | By far the easiest way to implement Rialto is to use RialtoActivity as the base class for your Activity. Don't worry that you need to extend AppCompatActivity - RialtoActivity is a subclass of that, so you'll automatically get it. The version of AppCompatActivity which will be used will depend upon the flavour of Rialto that you're using. For example rialto-androidx subclasses AppCompatActivity from the Android X version of AppCompat. There is also a way of implementing Rialto without subclassing RialtoActivity, and we'll look at that in a future article.
46 |
47 | The next thing that we need to do is register some factories which will be used to create spans whenever annotations are found with specific key /value pairs. It is important to do this before we inflate any layouts because the Rialto framework will perform text formatting during layout inflation, and we therefore need to register these factories first in order to apply the correct formatting. This example shows how we can register a couple of span types to handle bold and italic (yes, I realise that we can already apply these styles using <b> and <i> in our text resources, but the value behind re-implementing these using annotations will become apparent as we explore some slightly more complex examples):
48 |
49 | ```kotlin
50 | class MainActivity : RialtoActivity() {
51 |
52 | override fun onCreate(savedInstanceState: Bundle?) {
53 | super.onCreate(savedInstanceState)
54 | registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
55 | registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
56 | setContentView(R.layout.activity_main)
57 | }
58 | }
59 | ```
60 |
61 | RialtoActivity has a field named factory which is where we perform our registrations, and then we register a couple of span types to specific key value pairs. The lambda is a simple factory method which will create a span of the correct type. This example registers two spans: The first will be applied to any annotation with a key of "format" and a value of "bold" and will apply a bold StyleSpan to the text included within the annotation; the second will will be applied to any annotation with a key of "format" and a value of "italic" and will apply an italic StyleSpan to the text included within the annotation.
62 |
63 | Now we create a Layout with a single TextView:
64 |
65 | ```xml
66 |
67 |
73 |
74 |
83 |
84 |
85 | ```
86 |
87 | The string resource with the id @string/main_text
that we use for this TextView looks like this:
88 |
89 | ```xml
90 |
91 | ...
92 | This is a string containing both bold and italic text
93 | ...
94 |
95 | ```
96 | Note how the attributes of the <annotation ...>
elements matches the key / value pairs that we registered earlier.
97 |
98 | That's all we need to do, there's no need to manually do any processing, Rialto does it for us:
99 |
100 |
101 |
102 | It also works for EditText:
103 |
104 | ```xml
105 |
106 |
112 |
113 |
123 |
124 |
134 |
135 |
136 | ```
137 |
138 | This produces the following:
139 |
140 |
141 |
142 | Of course, you may not always wish to have formatting applied to all of your TextView and EditText instances within the layout. You can disable formatting by setting the annotationFormatting attribute to false:
143 |
144 | ```xml
145 |
146 |
152 |
153 |
163 |
164 |
174 |
175 |
187 |
188 |
200 |
201 |
202 | ```
203 |
204 | Using this attribute results in a lint warning, so where we use it we may need to disable the missingPrefix warning using tools:ignore="missingPrefix".
205 |
206 | We can see how we can selectively apply the formatting:
207 |
208 |
209 |
210 | #### Combining Spans
211 |
212 | One possible complexity when using annotation spans is that it is not possible to use the same key more than once in any specific annotation instance. In other words, if you have <annotation format="bold" format="underline">...</annotation>
within a string resource you'll get an error because XML does not support multiple attributes of the same name. One solution to this is to nest annotation elements one inside another, but this ends up becoming rather verbose and will bloat your string resources making them difficult to read.
213 |
214 | The mechanism that Rialto uses to allow multiple span types to be combined is that it allows you to set multiple span factories for any given key/value pair. The easiest way to demonstrate this is with an example:
215 |
216 |
217 | ```kotlin
218 | class MainActivity : RialtoActivity() {
219 |
220 | override fun onCreate(savedInstanceState: Bundle?) {
221 | super.onCreate(savedInstanceState)
222 | registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
223 | registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
224 | registerSpanFactory("format", "bold_underline") { StyleSpan(Typeface.BOLD) }
225 | registerSpanFactory("format", "bold_underline") { UnderlineSpan() }
226 | setContentView(R.layout.activity_main)
227 | }
228 | }
229 | ```
230 |
231 | Here we add two separate span factories for the key "format
" with the value "bold_underline
". When an annotation of <annotation format="bold_underline">...</annotation>
is encountered within a string resource, then both the bold and underline spans will be applied:
232 |
233 |
234 |
235 | Previously I mentioned that it would become apparent why it is better to apply formatting such as bold and italic using annotations spans rather than <b> and <i> and this is why. While we could achieve bold underline using <b><u>...</u></b> it would make it much harder to combine these kinds of formats with others which are not supported by the HTML style formatting. However if we use a consistent approach throughout our app, then we can easily combine formats as per this example.
236 |
237 | #### Cascading Registry
238 |
239 | Although Rialto is pretty easy to set up, it does need to be set up in each individual Activity. While this would not be so much of a problem for apps which have different visual styles for each Activity, but in many cases there will be certain annotations which would be useful to have available throughout the app. For this reason, V1.1.0 introduces a cascading Registry. The Rialto Registry is where all of the span factories are registered, and it is now possible to define a Registry within your Application instance. Any span factories that are registered directly to this Registry will be available to all of your Rialto Activities. You can register further span factories within each Activity, but these additions will only be available within the Activity itself. This provides great flexibility because you can define any common styles at application level, and then Activity-specific styles locally. Creating an Application Registry is pretty simple. You can either subclass RialtoApplication and register your global spans in onCreate()
:
240 |
241 |
242 | ```kotlin
243 | class KotlinApplication : RialtoApplication() {
244 |
245 | override fun onCreate() {
246 | super.onCreate()
247 | registerSpanFactory("format", "underline") { UnderlineSpan() }
248 | }
249 | }
250 | ```
251 |
252 | Alternatively, if you would prefer not to subclass RialtoApplication, you can implement things manually with just a few additional lines of code:
253 |
254 |
255 | ```kotlin
256 | class KotlinApplication @JvmOverloads constructor(
257 | registry: RialtoRegistry = Registry()
258 | ) : Application(), RialtoRegistry by registry {
259 |
260 | override fun onCreate() {
261 | super.onCreate()
262 | registerSpanFactory("format", "underline") { UnderlineSpan() }
263 | }
264 | }
265 | ```
266 |
267 | Kotlin delegation makes this really easy.
268 |
269 | If you are doing this from Java, then it is slightly more work still, but still nothing major - you just need to perform the delegation manually:
270 |
271 |
272 | ```java
273 | public class JavaApplication extends Application implements RialtoRegistry {
274 |
275 | private RialtoRegistry delegate = new Registry();
276 |
277 | @NotNull
278 | @Override
279 | public Set<Function0<Object>> get(@NotNull String key, @NotNull String value) {
280 | return delegate.get(key, value);
281 | }
282 |
283 | @Override
284 | public void registerSpanFactory(@NotNull String key, @NotNull String value, @NotNull Function0<?> creator) {
285 | delegate.registerSpanFactory(key, value, creator);
286 | }
287 |
288 | @NotNull
289 | @Override
290 | public RialtoRegistry copy() {
291 | return delegate.copy();
292 | }
293 |
294 | @Override
295 | public void onCreate() {
296 | super.onCreate();
297 | registerSpanFactory("format", "underline", UnderlineSpan::new);
298 | }
299 | }
300 | ```
301 |
302 | By doing this, any Activities which use Rialto will automatically get any span registrations that are made here - there's nothing more that you need to do!
303 |
304 | Currently it isn't possible to do this selectively for specific Activities - if you have an Application-level Registry, then all Activities will get it. If anyone needs this functionality please raise an issue and I'll look at adding an option to do this.
305 |
306 | #### Format Strings
307 |
308 | The other new feature introduced in Rialto 1.1.0 is the ability to load formatted strings containing annotations. Android only permits resource string formatting to be performed on simple string resources, so if you attempt to load a formatted String which contains annotations, then the annotations will be lost as it is loaded. Rialto 1.1.0 introduces an extension function to Resources which enables string resources containing formatting to be loaded as Spanned objects keeping the annotation spans intact. Rialto can then process these as normal.
309 |
310 | If we have the following string resource defined:
311 |
312 |
313 | ```xml
314 | This is a %1$s string
315 | ```
316 |
317 | This can be retrieved using the extension function with a set of format arguments which will be substituted in:
318 |
319 |
320 | ```kotlin
321 | val newText = resources.getFormattedText(R.string.formatted, "formatted")
322 | ```
323 |
324 | This takes the resource ID of the string and a varargs array of the values to use for the formatting. This works in the same way as Resources.getString(int id, Object... formatArgs) except that it returns a CharSequence with the annotations intact.
325 |
326 | The following string will be produced:
327 |
328 | ```
329 | This is a formatted string
330 | ```
331 |
332 | The annotation span will remain, and will have expanded so that it now surrounds the word "formatted" which was substituted in as part of the formatting. Provided that we have a span factory registered for the key 'format' and value 'bold' to match the annotation in the string resource, then Rialto will correctly format things:
333 |
334 |
335 |
336 | One limitation here is that annotations are only supported on the string resource itself. In other words they can be used in the string resource referenced by the first argument, but they cannot be used within any of the varargs parameters. Despite this limitation, this feature still provides some quite useful formatting of annotated strings.
337 |
338 | #### Downloadable Fonts
339 |
340 | Downloadable fonts have been around since the Oreo developer previews, and were made backwardly compatible Support Library 26, so there's really no reason not to be using them. When downloading these on-demand it is really important to add meta-data to the manifest so that these will get downloaded when your app is installed. This ensures that when your app is launched for the first time all of the required fonts have been downloaded to the device. I'm please to announce that there is now a mechanism to easily hook these in to Rialto so that you can use these in annotations.
341 |
342 | The key to this is by using the preloaded_fonts array that is used when pre-declaring the fonts in the manifest. This array will actually be generated for you automatically if you use the tools built in to Android Studio to manage downloadable fonts. It is this array that Rialto uses. A typical @arrays/preloaded_fonts
file looks something like this:
343 |
344 | ```xml
345 |
346 |
347 |
348 | - @font/audiowide
349 | - @font/pacifico
350 |
351 |
352 | ```
353 |
354 | This defines two fonts which are used by the app – named “audiowide” and “pacifico”. To hook these up to Rialto we use FontRegistrar which was added to Rialto V1.2.0. We can use this either within our Application instance to provide support throughout the app, or in individual Activities to limit availability to specific Activities. Here we are applying it to the Application:
355 |
356 | ```kotlin
357 | class KotlinApplication @JvmOverloads constructor(
358 | registry: RialtoRegistry = Registry()
359 | ) : Application(), RialtoRegistry by registry {
360 |
361 | override fun onCreate() {
362 | super.onCreate()
363 | registerSpanFactory("format", "underline") { UnderlineSpan() }
364 | FontRegistrar(this)
365 | .registerFonts(this, "font", R.array.preloaded_fonts)
366 | }
367 | }
368 | ```
369 |
370 | The FontRegistrar takes a single context as an argument. FontRegistrar contains a single method named registerFonts() which takes three arguments: The first is the RialtoRegistry to which the fonts will be added (RialtoDelegate implements RialtoRegistry so can be used here also); the second is the attribute name to which the fonts will be registered; and the third is the ID of the preloaded_fonts array. FontRegistrar will iterate through the array and register each font using the name from the second argument, and a value equal to the font name which will create a Span to use the relevant font wherever it is encountered.
371 |
372 | Using the preloaded_fonts array that we looked at earlier would result in two items being registered, one for each font. An example will show this in action and will probably be easier to understand that the dry description:
373 |
374 | ```xml
375 |
376 | This has two different fonts
377 |
378 | ```
379 |
380 | The attribute names match those of the second argument to the registerFonts() method, and the values correspond to the font names from the preloaded_fonts array. Running this results in:
381 |
382 |
383 |
384 | It is worth noting that since V1.2.0 Rialto is case insensitive, so using a font name of “Pacifico” is identical to using “pacifico”.
385 |
386 | There’s really nothing more to this – registering your preloaded_fonts array using FontRegistrar does all that you need, and you just need to use the appropriate annotations within your string resources to make use of them.
387 |
388 | #### Java Interoperability
389 |
390 | The other thing worth covering is how to use Rialto in cases where extending RialtoActivity is not possible. Your Activity must implement the RialtoDelegate interface, and needs to construct a RialtoDelegate instance to which it delegates all of the required behaviour:
391 |
392 |
393 | ```kotlin
394 | class MainActivity : AppCompatActivity(), RialtoDelegate {
395 | private lateinit var delegate: RialtoDelegate
396 |
397 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
398 | delegate.registerSpanFactory(key, value, creator)
399 | }
400 |
401 | override fun processAnnotations(text: CharSequence?): CharSequence? =
402 | delegate.processAnnotations(text)
403 |
404 | override fun onCreate(savedInstanceState: Bundle?) {
405 | delegate = RialtoDelegateImpl(this)
406 |
407 | super.onCreate(savedInstanceState)
408 | registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
409 | registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
410 | setContentView(R.layout.activity_main)
411 | }
412 | }
413 | ```
414 |
415 | Implementing RialtoDelegate requires the methods registerSpanFactory(key: String, value: String, creator: () -> Any)
and processAnnotations(text: CharSequence?): CharSequence?
to be implemented. All we need to do here is create an instance of RialtoDelegateImpl(this)
which we do in onCreate()
and then we can delegate both of these methods to the RialtoDelegateImpl instance. It is important to initialise this before the call to super.onCreate()
otherwise Rialto will not initialise correctly, and no processing of annotation in string resources will be performed.
416 |
417 | We can also do this from Java in much the same way:
418 |
419 |
420 | ```java
421 | public class MainActivity extends AppCompatActivity implements RialtoDelegate {
422 |
423 | private RialtoDelegate delegate = null;
424 |
425 | @Override
426 | public void registerSpanFactory(@NotNull String key, @NotNull String value, @NotNull Function0> creator) {
427 | delegate.registerSpanFactory(key, value, creator);
428 | }
429 |
430 | @Override
431 | public CharSequence processAnnotations(CharSequence text) {
432 | return delegate.processAnnotations(text);
433 | }
434 |
435 | @Override
436 | protected void onCreate(@Nullable Bundle savedInstanceState) {
437 | delegate = new RialtoDelegateImpl(this);
438 |
439 | super.onCreate(savedInstanceState);
440 |
441 | registerSpanFactory("format", "bold", new Function0() {
442 | @Override
443 | public CharacterStyle invoke() {
444 | return new StyleSpan(Typeface.BOLD);
445 | }
446 | });
447 | registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC));
448 | setContentView(R.layout.activity_main);
449 | }
450 | }
451 | ```
452 |
453 | The important differences here are with the method signatures of the methods from RialtoDelegate that we need to override. However, if you allow Android Studio to generate the method stubs for you once you have added implements RialtoDelegate to the MainActivity class, then you can't go far wrong.
454 |
455 | One last thing worth mentioning is that if you are using Rialto from Java there are a couple of things worth bearing in mind. Firstly, the mechanism for calling registerSpanFactory()
will vary depending on whether you are using Java 7 or Java 8:
456 |
457 | If you are using Java 7 then you will need to create a Function0 instance as the third argument to registerSpanFactory()
:
458 |
459 |
460 | ```java
461 | registerSpanFactory("format", "bold", new Function0() {
462 | @Override
463 | public CharacterStyle invoke() {
464 | return new StyleSpan(Typeface.BOLD);
465 | }
466 | });
467 | ```
468 |
469 |
470 | However if you are using Java 8 (or Retrolambda) then you can use a lambda instead:
471 |
472 | ```java
473 | registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC));
474 | ```
475 |
476 | The second thing that you will need to do is add the Kotlin standard library as a dependency to your project:
477 |
478 |
479 | ```groovy
480 | dependencies {
481 | ...
482 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
483 | ...
484 | }
485 | ```
486 |
487 | To use format strings from Java you will need to add a little extra code to access the extension function that gets exposed to Java:
488 |
489 | ```java
490 | SpannableFormatterKt.getFormattedText(getResources(), R.string.formatted_italic, "formatted")
491 | ```
492 |
493 | Rialto is written 100% in Kotlin, but can be used quite easily from Java. The only pre-requisite is that the Kotlin standard library is needed because it contains the Function0 class that is used for Java compatibility of Kotlin lambdas.
494 |
495 | #### Internals
496 |
497 | One final thing worth noting is that when Rialto does its stuff, it adds spans to the string resource, but does not remove the annotation spans as it goes. The reasoning behind this is that some use-cases may require some further processing of those annotations, and removing them would prevent this. Also, it is worth remembering that on a Spanned instance the individual Span objects are relatively small, so keeping the Annotation instances is not going to be a major memory issue.
498 |
499 | Rialto is really quite simple to use and the API surface is really quite small. Internally it isn't a particularly large or complex library, it's power is based upon creating the registry of span factories which apply the relevant spans whenever specific annotations are encountered.
500 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | apply from: 'dependencies.gradle'
5 |
6 | repositories {
7 | google()
8 | jcenter()
9 |
10 | }
11 | dependencies {
12 | classpath buildPlugins.androidGradlePlugin
13 | classpath buildPlugins.kotlinGradlePlugin
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | jcenter()
21 | }
22 | ext {
23 | groupId = "com.stylingandroid.rialto"
24 | libraryVersion = "1.2.0"
25 | libraryCode = 120
26 | siteUrl = 'https://github.com/StylingAndroid/Rialto'
27 | gitUrl = 'https://github.com/StylingAndroid/Rialto.git'
28 | }
29 | }
30 |
31 | task clean(type: Delete) {
32 | delete rootProject.buildDir
33 | }
34 |
--------------------------------------------------------------------------------
/common/res/font/audiowide.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/common/res/font/pacifico.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/common/res/values/font_certs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - @array/com_google_android_gms_fonts_certs_dev
5 | - @array/com_google_android_gms_fonts_certs_prod
6 |
7 |
8 | -
9 | MIIEqDCCA5CgAwIBAgIJANWFuGx90071MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAeFw0wODA0MTUyMzM2NTZaFw0zNTA5MDEyMzM2NTZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBANbOLggKv+IxTdGNs8/TGFy0PTP6DHThvbbR24kT9ixcOd9W+EaBPWW+wPPKQmsHxajtWjmQwWfna8mZuSeJS48LIgAZlKkpFeVyxW0qMBujb8X8ETrWy550NaFtI6t9+u7hZeTfHwqNvacKhp1RbE6dBRGWynwMVX8XW8N1+UjFaq6GCJukT4qmpN2afb8sCjUigq0GuMwYXrFVee74bQgLHWGJwPmvmLHC69EH6kWr22ijx4OKXlSIx2xT1AsSHee70w5iDBiK4aph27yH3TxkXy9V89TDdexAcKk/cVHYNnDBapcavl7y0RiQ4biu8ymM8Ga/nmzhRKya6G0cGw8CAQOjgfwwgfkwHQYDVR0OBBYEFI0cxb6VTEM8YYY6FbBMvAPyT+CyMIHJBgNVHSMEgcEwgb6AFI0cxb6VTEM8YYY6FbBMvAPyT+CyoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJANWFuGx90071MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBABnTDPEF+3iSP0wNfdIjIz1AlnrPzgAIHVvXxunW7SBrDhEglQZBbKJEk5kT0mtKoOD1JMrSu1xuTKEBahWRbqHsXclaXjoBADb0kkjVEJu/Lh5hgYZnOjvlba8Ld7HCKePCVePoTJBdI4fvugnL8TsgK05aIskyY0hKI9L8KfqfGTl1lzOv2KoWD0KWwtAWPoGChZxmQ+nBli+gwYMzM1vAkP+aayLe0a1EQimlOalO762r0GXO0ks+UeXde2Z4e+8S/pf7pITEI/tP+MxJTALw9QUWEv9lKTk+jkbqxbsh8nfBUapfKqYn0eidpwq2AzVp3juYl7//fKnaPhJD9gs=
10 |
11 |
12 |
13 | -
14 | MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDAeFw0wODA4MjEyMzEzMzRaFw0zNjAxMDcyMzEzMzRaMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBAKtWLgDYO6IIrgqWbxJOKdoR8qtW0I9Y4sypEwPpt1TTcvZApxsdyxMJZ2JORland2qSGT2y5b+3JKkedxiLDmpHpDsz2WCbdxgxRczfey5YZnTJ4VZbH0xqWVW/8lGmPav5xVwnIiJS6HXk+BVKZF+JcWjAsb/GEuq/eFdpuzSqeYTcfi6idkyugwfYwXFU1+5fZKUaRKYCwkkFQVfcAs1fXA5V+++FGfvjJ/CxURaSxaBvGdGDhfXE28LWuT9ozCl5xw4Yq5OGazvV24mZVSoOO0yZ31j7kYvtwYK6NeADwbSxDdJEqO4k//0zOHKrUiGYXtqw/A0LFFtqoZKFjnkCAQOjgdkwgdYwHQYDVR0OBBYEFMd9jMIhF1Ylmn/Tgt9r45jk14alMIGmBgNVHSMEgZ4wgZuAFMd9jMIhF1Ylmn/Tgt9r45jk14aloXikdjB0MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLR29vZ2xlIEluYy4xEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNVBAMTB0FuZHJvaWSCCQDC4IdGZEowjTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQBt0lLO74UwLDYKqs6Tm8/yzKkEu116FmH4rkaymUIE0P9KaMftGlMexFlaYjzmB2OxZyl6euNXEsQH8gjwyxCUKRJNexBiGcCEyj6z+a1fuHHvkiaai+KL8W1EyNmgjmyy8AW7P+LLlkR+ho5zEHatRbM/YAnqGcFh5iZBqpknHf1SKMXFh4dd239FJ1jWYfbMDMy3NS5CTMQ2XFI1MvcyUTdZPErjQfTbQe3aDQsQcafEQPD+nqActifKZ0Np0IS9L9kR/wbNvyz6ENwPiTrjV2KRkEjH78ZMcUQXg0L3BYHJ3lc69Vs5Ddf9uUGGMYldX3WfMBEmh/9iFBDAaTCK
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/common/res/values/preloaded_fonts.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - @font/audiowide
5 | - @font/pacifico
6 |
7 |
8 |
--------------------------------------------------------------------------------
/common/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | This is a string containing both bold, underlined, underlined bold, and italic text plus two different fonts
3 | This is a %1$s string
4 | This is a %1$s string
5 |
6 |
--------------------------------------------------------------------------------
/common/test/java/com/stylingandroid/rialto/app/MainActivityTest.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.graphics.Typeface
4 | import android.text.style.UnderlineSpan
5 | import androidx.test.espresso.Espresso.onView
6 | import androidx.test.espresso.assertion.ViewAssertions.matches
7 | import androidx.test.espresso.matcher.ViewMatchers.withId
8 | import androidx.test.ext.junit.runners.AndroidJUnit4
9 | import androidx.test.rule.ActivityTestRule
10 | import com.stylingandroid.rialto.format.getFormattedText
11 | import org.hamcrest.Matchers.not
12 | import org.junit.Rule
13 | import org.junit.Test
14 | import org.junit.runner.RunWith
15 |
16 | @RunWith(AndroidJUnit4::class)
17 | class MainActivityTest {
18 |
19 | @get:Rule
20 | val rule = ActivityTestRule(MainActivity::class.java)
21 |
22 | @Test
23 | fun `Given an inflated layout When we use default values Then a bold span surrounds the bold text of formatted_text_view`() {
24 | onView(withId(R.id.formatted_text_view)).check(
25 | matches(withSpan(withStyle(Typeface.BOLD), 33..36))
26 | )
27 | }
28 |
29 | @Test
30 | fun `Given an inflated layout When we use default values Then an italic span surrounds the italic text of formatted_text_view`() {
31 | onView(withId(R.id.formatted_text_view)).check(
32 | matches(withSpan(withStyle(Typeface.ITALIC), 72..77))
33 | )
34 | }
35 |
36 | @Test
37 | fun `Given an inflated layout When we use default values Then an underline span surrounds the underline text of formatted_text_view`() {
38 | onView(withId(R.id.formatted_text_view)).check(
39 | matches(withSpan(withType(UnderlineSpan::class.java), 39..48))
40 | )
41 | }
42 |
43 | @Test
44 | fun `Given an inflated layout When we use default values Then a bold span surrounds the bold underline text of formatted_text_view`() {
45 | onView(withId(R.id.formatted_text_view)).check(
46 | matches(withSpan(withStyle(Typeface.BOLD), 51..65))
47 | )
48 | }
49 |
50 | @Test
51 | fun `Given an inflated layout When we use default values Then an underline span surrounds the bold underline text of formatted_text_view`() {
52 | onView(withId(R.id.formatted_text_view)).check(
53 | matches(withSpan(withType(UnderlineSpan::class.java), 51..65))
54 | )
55 | }
56 |
57 | @Test
58 | fun `Given an inflated layout When we use default values Then a pacifico typeface span surrounds the pacifico text of formatted_text_view`() {
59 | onView(withId(R.id.formatted_text_view)).check(
60 | matches(withSpan(withTypeface(), 89..91))
61 | )
62 | }
63 |
64 | @Test
65 | fun `Given an inflated layout When we use default values Then a audiowide typeface span surrounds the audiowide text of formatted_text_view`() {
66 | onView(withId(R.id.formatted_text_view)).check(
67 | matches(withSpan(withTypeface(), 93..101))
68 | )
69 | }
70 |
71 | @Test
72 | fun `Given an inflated layout When we use default values Then a bold span surrounds the bold text of formatted_edit_text`() {
73 | onView(withId(R.id.formatted_edit_text)).check(
74 | matches(withSpan(withStyle(Typeface.BOLD), 33..36))
75 | )
76 | }
77 |
78 | @Test
79 | fun `Given an inflated layout When we use default values Then an italic span surrounds the italic text of formatted_edit_text`() {
80 | onView(withId(R.id.formatted_edit_text)).check(
81 | matches(withSpan(withStyle(Typeface.ITALIC), 72..77))
82 | )
83 | }
84 |
85 |
86 | @Test
87 | fun `Given an inflated layout When we use default values Then an underline span surrounds the underline text of formatted_edit_text`() {
88 | onView(withId(R.id.formatted_edit_text)).check(
89 | matches(withSpan(withType(UnderlineSpan::class.java), 39..48))
90 | )
91 | }
92 |
93 | @Test
94 | fun `Given an inflated layout When we use default values Then a bold span surrounds the bold underline text of formatted_edit_text`() {
95 | onView(withId(R.id.formatted_edit_text)).check(
96 | matches(withSpan(withStyle(Typeface.BOLD), 51..65))
97 | )
98 | }
99 |
100 | @Test
101 | fun `Given an inflated layout When we use default values Then a pacifico typeface span surrounds the pacifico text of formatted_edit_text`() {
102 | onView(withId(R.id.formatted_edit_text)).check(
103 | matches(withSpan(withTypeface(), 89..91))
104 | )
105 | }
106 |
107 | @Test
108 | fun `Given an inflated layout When we use default values Then a audiowide typeface span surrounds the audiowide text of formatted_edit_text`() {
109 | onView(withId(R.id.formatted_edit_text)).check(
110 | matches(withSpan(withTypeface(), 93..101))
111 | )
112 | }
113 |
114 | @Test
115 | fun `Given an inflated layout When we use default values Then an underline span surrounds the bold underline text of formatted_edit_text`() {
116 | onView(withId(R.id.formatted_edit_text)).check(
117 | matches(withSpan(withType(UnderlineSpan::class.java), 51..65))
118 | )
119 | }
120 |
121 | @Test
122 | fun `Given an inflated layout When we use default values Then a bold span does not get added to the text of unformatted_text_view`() {
123 | onView(withId(R.id.unformatted_text_view)).check(
124 | matches(not(withSpan(withStyle(Typeface.BOLD))))
125 | )
126 | }
127 |
128 | @Test
129 | fun `Given an inflated layout When we use default values Then a italic span does not get added to the text of unformatted_text_view`() {
130 | onView(withId(R.id.unformatted_text_view)).check(
131 | matches(not(withSpan(withStyle(Typeface.ITALIC))))
132 | )
133 | }
134 |
135 | @Test
136 | fun `Given an inflated layout When we use default values Then a underline span does not get added to the text of unformatted_text_view`() {
137 | onView(withId(R.id.unformatted_text_view)).check(
138 | matches(not(withSpan(withType(UnderlineSpan::class.java))))
139 | )
140 | }
141 |
142 | @Test
143 | fun `Given an inflated layout When we use default values Then a pacifico typeface span surrounds the pacifico text of unformatted_text_view`() {
144 | onView(withId(R.id.unformatted_text_view)).check(
145 | matches(not(withSpan(withTypeface(), 89..91)))
146 | )
147 | }
148 |
149 | @Test
150 | fun `Given an inflated layout When we use default values Then a audiowide typeface span surrounds the audiowide text of unformatted_text_view`() {
151 | onView(withId(R.id.unformatted_text_view)).check(
152 | matches(not(withSpan(withTypeface(), 93..101)))
153 | )
154 | }
155 |
156 | @Test
157 | fun `Given an inflated layout When we use default values Then a bold span does not get added to the text of unformatted_edit_text`() {
158 | onView(withId(R.id.unformatted_edit_text)).check(
159 | matches(not(withSpan(withStyle(Typeface.BOLD))))
160 | )
161 | }
162 |
163 | @Test
164 | fun `Given an inflated layout When we use default values Then a italic span does not get added to the text of unformatted_edit_text`() {
165 | onView(withId(R.id.unformatted_edit_text)).check(
166 | matches(not(withSpan(withStyle(Typeface.ITALIC))))
167 | )
168 | }
169 |
170 | @Test
171 | fun `Given an inflated layout When we use default values Then a underline span does not get added to the text of unformatted_edit_text`() {
172 | onView(withId(R.id.unformatted_edit_text)).check(
173 | matches(not(withSpan(withType(UnderlineSpan::class.java))))
174 | )
175 | }
176 |
177 | @Test
178 | fun `Given an inflated layout When we use default values Then a pacifico typeface span surrounds the pacifico text of unformatted_edit_text`() {
179 | onView(withId(R.id.unformatted_edit_text)).check(
180 | matches(not(withSpan(withTypeface(), 89..91)))
181 | )
182 | }
183 |
184 | @Test
185 | fun `Given an inflated layout When we use default values Then a audiowide typeface span surrounds the audiowide text of unformatted_edit_text`() {
186 | onView(withId(R.id.unformatted_edit_text)).check(
187 | matches(not(withSpan(withTypeface(), 93..101)))
188 | )
189 | }
190 |
191 | @Test
192 | fun `Given an inflated layout When we set text on formatted_text_view using a formatted string Then an italic span is added`() {
193 | onView(withId(R.id.format_string))
194 | .check(matches(withSpan(withStyle(Typeface.ITALIC), 10..18)))
195 | }
196 |
197 | @Test
198 | fun `Given an inflated layout When we set text on formatted_text_view using a different formatted string Then a bold span is added`() {
199 | val newText = rule.activity.resources.getFormattedText(R.string.formatted_bold, "formatted")
200 | onView(withId(R.id.format_string))
201 | .perform(setText(newText))
202 | .check(matches(withSpan(withStyle(Typeface.BOLD), 10..18)))
203 | }
204 |
205 | @Test
206 | fun `Given an inflated layout When we set text on unformatted_text_view using a formatted string Then a bold span is not added`() {
207 | val newText = rule.activity.resources.getFormattedText(R.string.formatted_bold, "formatted")
208 | onView(withId(R.id.unformatted_text_view))
209 | .perform(setText(newText))
210 | .check(matches(not(withSpan(withStyle(Typeface.BOLD)))))
211 | }
212 | }
213 |
--------------------------------------------------------------------------------
/common/test/java/com/stylingandroid/rialto/app/SpanMatcher.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.text.style.StyleSpan
4 | import com.stylingandroid.rialto.font.CustomTypefaceSpan
5 | import org.hamcrest.BaseMatcher
6 | import org.hamcrest.Description
7 |
8 | fun withSpan(type: SpanTypeMatcher<*>) =
9 | SpanMatcher(type)
10 |
11 | fun withSpan(type: SpanTypeMatcher<*>, range: ClosedRange) =
12 | SpanMatcher(type, range)
13 |
14 | fun withStyle(style: Int) = StyleSpanMatcher(style)
15 |
16 | class StyleSpanMatcher(private val style: Int) : SpanTypeMatcher(StyleSpan::class.java) {
17 |
18 | override fun describeTo(description: Description?) {
19 | description?.appendText("with style:")?.appendValue(style)
20 | }
21 |
22 | override fun matches(item: Any?): Boolean =
23 | ((item as? StyleSpan)?.style == style)
24 | }
25 |
26 | fun withType(classType: Class<*>) = SpanTypeMatcher(classType)
27 |
28 | open class SpanTypeMatcher(val classType: Class<*>) : BaseMatcher() {
29 |
30 | override fun describeTo(description: Description?) {
31 | description?.appendText(" with type: ")?.appendValue(classType.simpleName)
32 | }
33 |
34 | override fun matches(item: Any?): Boolean = classType.isInstance(item)
35 | }
36 |
37 | fun setText(charSequence: CharSequence) =
38 | SetTextAction(charSequence)
39 |
40 |
41 | fun withTypeface() = SpanTypeMatcher(CustomTypefaceSpan::class.java)
42 |
--------------------------------------------------------------------------------
/common/testCommonx/java/com/stylingandroid/rialto.app/AndroidXSpanMatcher.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.content.Context
4 | import android.graphics.Typeface
5 | import android.text.Spanned
6 | import android.text.style.TypefaceSpan
7 | import android.view.View
8 | import android.widget.TextView
9 | import androidx.core.content.res.ResourcesCompat
10 | import androidx.test.espresso.UiController
11 | import androidx.test.espresso.ViewAction
12 | import androidx.test.espresso.matcher.BoundedMatcher
13 | import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom
14 | import com.stylingandroid.rialto.androidx.widget.RialtoTextView
15 | import org.hamcrest.BaseMatcher
16 | import org.hamcrest.Description
17 | import org.hamcrest.Matcher
18 |
19 | class SpanMatcher(
20 | private val type: SpanTypeMatcher<*>,
21 | private val range: ClosedRange? = null
22 | ) : BoundedMatcher(TextView::class.java) {
23 |
24 | override fun describeTo(description: Description?) {
25 | description?.appendText(" with span of type:")?.appendValue(type)
26 | description?.appendText(" in range:")?.appendValue(range)
27 | }
28 |
29 | override fun matchesSafely(item: TextView): Boolean {
30 | (item.text as? Spanned)?.also { spanned ->
31 | println("$spanned: ${type.classType.simpleName}")
32 | spanned.getSpans(0, spanned.length, type.classType).forEach { span ->
33 | println("$spanned: ${spanned.getSpanStart(span)}..${spanned.getSpanEnd(span)} ${span.javaClass.simpleName}")
34 | range?.also {
35 | if (spanned.getSpanStart(span) == range.start && spanned.getSpanEnd(span) == range.endInclusive + 1) {
36 | return type.matches(span)
37 | }
38 | } ?: return true
39 | }
40 | }
41 | return false
42 | }
43 | }
44 |
45 | class SetTextAction(private val charSequence: CharSequence) : ViewAction {
46 |
47 | override fun getDescription(): String = "replace text"
48 |
49 | override fun getConstraints(): Matcher =
50 | isAssignableFrom(RialtoTextView::class.java)
51 |
52 | override fun perform(uiController: UiController?, view: View?) {
53 | (view as? RialtoTextView)?.setText(charSequence, TextView.BufferType.SPANNABLE)
54 | }
55 | }
56 |
57 | class TypefaceSpanMatcher(private val context: Context, private val typefaceName: String) : BaseMatcher() {
58 | override fun describeTo(description: Description?) {
59 | description?.appendText("typeface name:")?.appendValue(typefaceName)
60 | }
61 |
62 | override fun matches(item: Any?): Boolean {
63 | val expected: Typeface? = context.resources.getIdentifier("font", typefaceName, context.packageName).let { id ->
64 | ResourcesCompat.getFont(context, id)
65 | }
66 | return (item as? TypefaceSpan)?.typeface?.equals(expected) ?: false
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/common/testCommonx/java/com/stylingandroid/rialto.app/ShadowResourcesCompat.java:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 | import android.graphics.Typeface;
6 | import androidx.annotation.FontRes;
7 | import androidx.annotation.NonNull;
8 | import androidx.core.content.res.ResourcesCompat;
9 | import org.robolectric.annotation.Implementation;
10 | import org.robolectric.annotation.Implements;
11 |
12 | @Implements(ResourcesCompat.class)
13 | public class ShadowResourcesCompat {
14 |
15 | @Implementation
16 | public static Typeface getFont(@NonNull Context context, @FontRes int id) throws Resources.NotFoundException {
17 | return Typeface.DEFAULT;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/common/testCommonx/resources/robolectric.properties:
--------------------------------------------------------------------------------
1 | shadows=com.stylingandroid.rialto.app.ShadowResourcesCompat
2 |
--------------------------------------------------------------------------------
/common/testSupport/java/com/stylingandroid/rialto/app/ShadowResourcesCompat.java:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 | import android.graphics.Typeface;
6 | import android.support.v4.content.res.ResourcesCompat;
7 | import androidx.annotation.FontRes;
8 | import androidx.annotation.NonNull;
9 | import org.robolectric.annotation.Implementation;
10 | import org.robolectric.annotation.Implements;
11 |
12 | @Implements(ResourcesCompat.class)
13 | public class ShadowResourcesCompat {
14 |
15 | @Implementation
16 | public static Typeface getFont(@NonNull Context context, @FontRes int id) throws Resources.NotFoundException {
17 | return Typeface.DEFAULT;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/common/testSupport/java/com/stylingandroid/rialto/app/SupportSpanMatcher.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.content.Context
4 | import android.graphics.Typeface
5 | import android.support.test.espresso.matcher.BoundedMatcher
6 | import android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom
7 | import android.support.v4.content.res.ResourcesCompat
8 | import android.text.Spanned
9 | import android.text.style.TypefaceSpan
10 | import android.view.View
11 | import android.widget.TextView
12 | import androidx.test.espresso.UiController
13 | import androidx.test.espresso.ViewAction
14 | import com.stylingandroid.rialto.support.widget.RialtoTextView
15 | import org.hamcrest.Description
16 | import org.hamcrest.Matcher
17 |
18 | class SpanMatcher(
19 | private val type: SpanTypeMatcher<*>,
20 | private val range: ClosedRange? = null
21 | ) : BoundedMatcher(TextView::class.java) {
22 |
23 | override fun describeTo(description: Description?) {
24 | description?.appendText(" with span of type:")?.appendValue(type)
25 | description?.appendText(" in range:")?.appendValue(range)
26 | }
27 |
28 | override fun matchesSafely(item: TextView?): Boolean {
29 | (item?.text as? Spanned)?.also { spanned ->
30 | spanned.getSpans(0, spanned.length, type.classType).forEach { span ->
31 | //println("Span: $type ${spanned.getSpanStart(span)}..${spanned.getSpanEnd(span)}")
32 | range?.also {
33 | if (spanned.getSpanStart(span) == range.start && spanned.getSpanEnd(span) == range.endInclusive + 1) {
34 | return type.matches(span)
35 | }
36 | } ?: return true
37 | }
38 | }
39 | return false
40 | }
41 | }
42 |
43 | class SetTextAction(private val charSequence: CharSequence) : ViewAction {
44 |
45 | override fun getDescription(): String = "replace text"
46 |
47 | override fun getConstraints(): Matcher =
48 | isAssignableFrom(RialtoTextView::class.java)
49 |
50 | override fun perform(uiController: UiController?, view: View?) {
51 | (view as? RialtoTextView)?.setText(charSequence, TextView.BufferType.SPANNABLE)
52 | }
53 | }
54 |
55 | class TypefaceSpanMatcher(private val context: Context, private val typefaceName: String) :
56 | SpanTypeMatcher(TypefaceSpan::class.java) {
57 | override fun describeTo(description: Description?) {
58 | description?.appendText("typeface name:")?.appendValue(typefaceName)
59 | }
60 |
61 | override fun matches(item: Any?): Boolean {
62 | val expected: Typeface? = context.resources.getIdentifier("font", typefaceName, context.packageName).let { id ->
63 | ResourcesCompat.getFont(context, id)
64 | }
65 | return (item as? TypefaceSpan)?.typeface?.equals(expected) ?: false
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/common/testSupport/resources/robolectric.properties:
--------------------------------------------------------------------------------
1 | shadows=com.stylingandroid.rialto.app.ShadowResourcesCompat
2 |
--------------------------------------------------------------------------------
/dependencies.gradle:
--------------------------------------------------------------------------------
1 | ext {
2 | androidMinSdkVersion = 16
3 | androidTargetSdkVersion = 28
4 | androidCompileSdkVersion = 28
5 |
6 | androidBuildToolsVersion = '3.4.0-alpha08'
7 |
8 | supportLibraryVersion = '28.0.0'
9 | androidXLibraryVersion = '1.0.2'
10 | constraintLayoutVersion = '1.1.3'
11 | materialVersion = '1.0.0-alpha1'
12 | kotlinVersion = '1.3.10'
13 | kotlinCoroutinesVersion = '1.0.1'
14 |
15 | junit4Version = '4.12'
16 | mockitoVersion = '2.23.0'
17 | mockitoKotlinVersion = '2.0.0'
18 | robolectricVersion = '4.0.2'
19 |
20 | androidXRunnerVersion = '1.0.0'
21 | androidXEspressoVersion = '3.1.0'
22 | androidXEspressoRulesVersion = '1.1.0'
23 | supportRunnerVersion = '1.0.2'
24 | supportEspressoVersion = '3.0.2'
25 | supportEspressoRulesVersion = '1.0.1'
26 |
27 | buildPlugins = [
28 | androidGradlePlugin: "com.android.tools.build:gradle:$androidBuildToolsVersion",
29 | kotlinGradlePlugin : "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
30 | ]
31 |
32 | libraries = [
33 | kotlinStdLib : "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion",
34 | kotlinCoroutinesCore : "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutinesVersion",
35 | kotlinCoroutinesAndroid: "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinCoroutinesVersion",
36 | material : "com.google.android.material:material:$materialVersion"
37 | ]
38 |
39 | androidXLibraries = [
40 | appCompat : "androidx.appcompat:appcompat:$androidXLibraryVersion",
41 | constraintLayout: "androidx.constraintlayout:constraintlayout:$constraintLayoutVersion"
42 | ]
43 |
44 | supportLibraries = [
45 | appCompat : "com.android.support:appcompat-v7:$supportLibraryVersion",
46 | constraintLayout: "com.android.support.constraint:constraint-layout:$constraintLayoutVersion"
47 | ]
48 |
49 | testLibraries = [
50 | junit4 : "junit:junit:$junit4Version",
51 | mockitoCore : "org.mockito:mockito-core:$mockitoVersion",
52 | kotlinTestJunit : "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion",
53 | mockitoKotlin : "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockitoKotlinVersion",
54 | robolectric : "org.robolectric:robolectric:$robolectricVersion",
55 | androidXRunner : "androidx.test.ext:junit:$androidXRunnerVersion",
56 | androidXEspressoCore : "androidx.test.espresso:espresso-core:$androidXEspressoVersion",
57 | androidXEspressoRules: "androidx.test:rules:$androidXEspressoRulesVersion",
58 | supportRunner : "com.android.support.test:runner:$supportRunnerVersion",
59 | supportEspressoCore : "com.android.support.test.espresso:espresso-core:$supportEspressoVersion",
60 | supportEspressoRules : "com.android.support.test:rules:$supportEspressoRulesVersion"
61 | ]
62 | }
63 |
--------------------------------------------------------------------------------
/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=-Xmx1536m
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 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=false
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 | org.gradle.parallel=true
23 | android.enableUnitTestBinaryResources=true
24 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Nov 17 12:18:00 GMT 2018
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-5.1-rc-1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/images/bold_underline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/images/bold_underline.png
--------------------------------------------------------------------------------
/images/disable_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/images/disable_example.png
--------------------------------------------------------------------------------
/images/downloadable_fonts.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/images/downloadable_fonts.png
--------------------------------------------------------------------------------
/images/edit_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/images/edit_example.png
--------------------------------------------------------------------------------
/images/simple_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/images/simple_example.png
--------------------------------------------------------------------------------
/javaApp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/javaApp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 |
4 | android {
5 | compileSdkVersion androidCompileSdkVersion
6 | defaultConfig {
7 | applicationId "com.stylingandroid.rialto.app"
8 | minSdkVersion androidMinSdkVersion
9 | targetSdkVersion androidTargetSdkVersion
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-optimize.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | flavorDimensions "libtype"
21 |
22 | productFlavors {
23 | support {
24 | dimension "libtype"
25 | applicationIdSuffix ".support"
26 | }
27 | androidx {
28 | dimension "libtype"
29 | applicationIdSuffix ".androidx"
30 | }
31 | material {
32 | dimension "libtype"
33 | applicationIdSuffix ".material"
34 | }
35 | }
36 | sourceSets {
37 | androidx.res.srcDirs += '../common/res'
38 | material.res.srcDirs += '../common/res'
39 | support.res.srcDirs += '../common/res'
40 | testAndroidx {
41 | java.srcDirs += ['../common/testCommonx/java', "../common/test/java"]
42 | resources.srcDir '../common/testCommonx/resources'
43 | }
44 | testMaterial {
45 | java.srcDirs += ['../common/testCommonx/java', "../common/test/java"]
46 | resources.srcDir '../common/testCommonx/resources'
47 | }
48 | testSupport {
49 | java.srcDirs += ['../common/testSupport/java', "../common/test/java"]
50 | resources.srcDir '../common/testSupport/resources'
51 | }
52 | }
53 | compileOptions {
54 | sourceCompatibility = '1.8'
55 | targetCompatibility = '1.8'
56 | }
57 | testOptions {
58 | unitTests.includeAndroidResources = true
59 | }
60 | }
61 |
62 | dependencies {
63 | implementation libraries.kotlinStdLib
64 | implementation project(path: ':library')
65 | androidxImplementation androidXLibraries.appCompat
66 | androidxImplementation androidXLibraries.constraintLayout
67 | supportImplementation supportLibraries.appCompat
68 | supportImplementation supportLibraries.constraintLayout
69 | materialImplementation libraries.material
70 | materialImplementation androidXLibraries.constraintLayout
71 | testImplementation testLibraries.robolectric
72 | testImplementation testLibraries.androidXRunner
73 | testImplementation testLibraries.androidXEspressoCore
74 | testImplementation testLibraries.androidXEspressoRules
75 | testImplementation testLibraries.supportRunner
76 | testImplementation testLibraries.supportEspressoCore
77 | testImplementation testLibraries.supportEspressoRules
78 | testImplementation testLibraries.mockitoCore
79 | testImplementation testLibraries.mockitoKotlin
80 | }
81 |
--------------------------------------------------------------------------------
/javaApp/lint.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/javaApp/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/javaApp/src/androidx/java/com/stylingandroid/rialto/app/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app;
2 |
3 | import android.graphics.Typeface;
4 | import android.os.Bundle;
5 | import android.text.style.CharacterStyle;
6 | import android.text.style.StyleSpan;
7 | import android.text.style.UnderlineSpan;
8 | import android.widget.TextView;
9 |
10 | import com.stylingandroid.rialto.RialtoDelegate;
11 | import com.stylingandroid.rialto.RialtoDelegateImpl;
12 | import com.stylingandroid.rialto.RialtoRegistry;
13 | import com.stylingandroid.rialto.format.SpannableFormatterKt;
14 |
15 | import org.jetbrains.annotations.NotNull;
16 |
17 | import androidx.annotation.Nullable;
18 | import androidx.appcompat.app.AppCompatActivity;
19 | import kotlin.jvm.functions.Function0;
20 |
21 | import java.util.Set;
22 |
23 | public class MainActivity extends AppCompatActivity implements RialtoDelegate {
24 |
25 | private RialtoDelegate delegate = null;
26 |
27 | @Override
28 | public void registerSpanFactory(@NotNull String key, @NotNull String value, @NotNull Function0> creator) {
29 | delegate.registerSpanFactory(key, value, creator);
30 | }
31 |
32 | @Override
33 | public CharSequence processAnnotations(CharSequence text) {
34 | return delegate.processAnnotations(text);
35 | }
36 |
37 | @NotNull
38 | @Override
39 | public Set> get(@NotNull String key, @NotNull String value) {
40 | return delegate.get(key, value);
41 | }
42 |
43 | @NotNull
44 | @Override
45 | public RialtoRegistry copy() {
46 | return delegate.copy();
47 | }
48 |
49 | @Override
50 | protected void onCreate(@Nullable Bundle savedInstanceState) {
51 | delegate = new RialtoDelegateImpl(this);
52 |
53 | super.onCreate(savedInstanceState);
54 |
55 | registerSpanFactory("format", "bold", new Function0() {
56 | @Override
57 | public CharacterStyle invoke() {
58 | return new StyleSpan(Typeface.BOLD);
59 | }
60 | });
61 | registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC));
62 | registerSpanFactory("format", "bold_underline", () -> new StyleSpan(Typeface.BOLD));
63 | registerSpanFactory("format", "bold_underline", UnderlineSpan::new);
64 | setContentView(R.layout.activity_main);
65 |
66 | TextView textView = findViewById(R.id.format_string);
67 | textView.setText(SpannableFormatterKt.getFormattedText(getResources(), R.string.formatted_italic, "formatted"));
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/javaApp/src/androidx/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
31 |
32 |
44 |
45 |
58 |
59 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/javaApp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/javaApp/src/main/java/com/stylingandroid/rialto/app/JavaApplication.java:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app;
2 |
3 | import android.app.Application;
4 | import android.text.style.UnderlineSpan;
5 | import com.stylingandroid.rialto.Registry;
6 | import com.stylingandroid.rialto.RialtoRegistry;
7 | import com.stylingandroid.rialto.font.FontRegistrar;
8 | import kotlin.jvm.functions.Function0;
9 | import org.jetbrains.annotations.NotNull;
10 |
11 | import java.util.Set;
12 |
13 | public class JavaApplication extends Application implements RialtoRegistry {
14 |
15 | private RialtoRegistry delegate = new Registry();
16 |
17 | @NotNull
18 | @Override
19 | public Set> get(@NotNull String key, @NotNull String value) {
20 | return delegate.get(key, value);
21 | }
22 |
23 | @Override
24 | public void registerSpanFactory(@NotNull String key, @NotNull String value, @NotNull Function0> creator) {
25 | delegate.registerSpanFactory(key, value, creator);
26 | }
27 |
28 | @NotNull
29 | @Override
30 | public RialtoRegistry copy() {
31 | return delegate.copy();
32 | }
33 |
34 | @Override
35 | public void onCreate() {
36 | super.onCreate();
37 | registerSpanFactory("format", "underline", UnderlineSpan::new);
38 | new FontRegistrar(this).registerFonts(this, "font", R.array.preloaded_fonts);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
32 |
33 |
34 |
35 |
36 |
37 |
41 |
45 |
46 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
17 |
24 |
31 |
38 |
45 |
52 |
59 |
66 |
73 |
80 |
87 |
94 |
101 |
108 |
115 |
116 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/javaApp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/javaApp/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #1E9618
4 | #4EE147
5 | #156912
6 |
7 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Rialto
3 |
4 |
--------------------------------------------------------------------------------
/javaApp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/javaApp/src/material/java/com/stylingandroid/rialto/app/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app;
2 |
3 | import android.graphics.Typeface;
4 | import android.os.Bundle;
5 | import android.text.style.CharacterStyle;
6 | import android.text.style.StyleSpan;
7 | import android.text.style.UnderlineSpan;
8 | import android.widget.TextView;
9 | import androidx.annotation.Nullable;
10 | import androidx.appcompat.app.AppCompatActivity;
11 | import com.stylingandroid.rialto.RialtoDelegate;
12 | import com.stylingandroid.rialto.RialtoDelegateImpl;
13 | import com.stylingandroid.rialto.RialtoRegistry;
14 | import com.stylingandroid.rialto.format.SpannableFormatterKt;
15 | import kotlin.jvm.functions.Function0;
16 | import org.jetbrains.annotations.NotNull;
17 |
18 | import java.util.Set;
19 |
20 | public class MainActivity extends AppCompatActivity implements RialtoDelegate {
21 |
22 | private RialtoDelegate delegate = null;
23 |
24 | @Override
25 | public void registerSpanFactory(@NotNull String key, @NotNull String value, @NotNull Function0> creator) {
26 | delegate.registerSpanFactory(key, value, creator);
27 | }
28 |
29 | @Override
30 | public CharSequence processAnnotations(CharSequence text) {
31 | return delegate.processAnnotations(text);
32 | }
33 |
34 |
35 | @NotNull
36 | @Override
37 | public Set> get(@NotNull String key, @NotNull String value) {
38 | return delegate.get(key, value);
39 | }
40 |
41 | @NotNull
42 | @Override
43 | public RialtoRegistry copy() {
44 | return delegate.copy();
45 | }
46 |
47 | @Override
48 | protected void onCreate(@Nullable Bundle savedInstanceState) {
49 | delegate = new RialtoDelegateImpl(this);
50 | registerSpanFactory("format", "bold", new Function0() {
51 | @Override
52 | public CharacterStyle invoke() {
53 | return new StyleSpan(Typeface.BOLD);
54 | }
55 | });
56 | registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC));
57 | registerSpanFactory("format", "bold_underline", () -> new StyleSpan(Typeface.BOLD));
58 | registerSpanFactory("format", "bold_underline", UnderlineSpan::new);
59 | super.onCreate(savedInstanceState);
60 | setContentView(R.layout.activity_main);
61 |
62 | TextView textView = findViewById(R.id.format_string);
63 | textView.setText(SpannableFormatterKt.getFormattedText(getResources(), R.string.formatted_italic, "formatted"));
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/javaApp/src/material/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
32 |
33 |
45 |
46 |
59 |
60 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/javaApp/src/material/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/javaApp/src/support/java/com/stylingandroid/rialto/app/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app;
2 |
3 | import android.graphics.Typeface;
4 | import android.os.Bundle;
5 | import android.text.style.CharacterStyle;
6 | import android.text.style.StyleSpan;
7 | import android.text.style.UnderlineSpan;
8 | import android.widget.TextView;
9 |
10 | import com.stylingandroid.rialto.format.SpannableFormatterKt;
11 |
12 | import kotlin.jvm.functions.Function0;
13 |
14 | public class MainActivity extends RialtoActivity {
15 |
16 | @Override
17 | protected void onCreate(Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 | registerSpanFactory("format", "bold", new Function0() {
20 | @Override
21 | public CharacterStyle invoke() {
22 | return new StyleSpan(Typeface.BOLD);
23 | }
24 | });
25 | registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC) );
26 | registerSpanFactory("format", "bold_underline", () -> new StyleSpan(Typeface.BOLD));
27 | registerSpanFactory("format", "bold_underline", UnderlineSpan::new);
28 | setContentView(R.layout.activity_main);
29 |
30 | TextView textView = findViewById(R.id.format_string);
31 | textView.setText(SpannableFormatterKt.getFormattedText(getResources(), R.string.formatted_italic, "formatted"));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/javaApp/src/support/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
32 |
33 |
45 |
46 |
59 |
60 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/kotlinApp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/kotlinApp/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "io.gitlab.arturbosch.detekt" version "1.0.0-RC11"
3 | }
4 |
5 | apply plugin: 'com.android.application'
6 | apply plugin: 'kotlin-android'
7 | apply plugin: 'kotlin-android-extensions'
8 |
9 | android {
10 | compileSdkVersion 28
11 | defaultConfig {
12 | applicationId "com.stylingandroid.rialto.app"
13 | minSdkVersion 16
14 | targetSdkVersion 28
15 | versionCode 1
16 | versionName "1.0"
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | flavorDimensions "libtype"
26 |
27 | productFlavors {
28 | support {
29 | dimension "libtype"
30 | applicationIdSuffix ".support"
31 | }
32 | androidx {
33 | dimension "libtype"
34 | applicationIdSuffix ".androidx"
35 | }
36 | material {
37 | dimension "libtype"
38 | applicationIdSuffix ".material"
39 | }
40 | }
41 | sourceSets {
42 | androidx.res.srcDirs += '../common/res'
43 | material.res.srcDirs += '../common/res'
44 | support.res.srcDirs += '../common/res'
45 | testAndroidx {
46 | java.srcDirs += ['../common/testCommonx/java', "../common/test/java"]
47 | resources.srcDir '../common/testCommonx/resources'
48 | }
49 | testMaterial {
50 | java.srcDirs += ['../common/testCommonx/java', "../common/test/java"]
51 | resources.srcDir '../common/testCommonx/resources'
52 | }
53 | testSupport {
54 | java.srcDirs += ['../common/testSupport/java', "../common/test/java"]
55 | resources.srcDir '../common/testSupport/resources'
56 | }
57 | }
58 | compileOptions {
59 | sourceCompatibility = '1.8'
60 | targetCompatibility = '1.8'
61 | }
62 |
63 | useLibrary 'android.test.runner'
64 |
65 | useLibrary 'android.test.base'
66 | useLibrary 'android.test.mock'
67 | testOptions {
68 | unitTests.includeAndroidResources = true
69 | }
70 | }
71 |
72 | detekt {
73 | version = "1.0.0-RC11"
74 | input = files("src/main/java", "src/androidx/java", "src/support/java")
75 | filters = ".*test.*,.*/resources/.*,.*/tmp/.*"
76 | }
77 |
78 | dependencies {
79 | implementation libraries.kotlinStdLib
80 | implementation project(path: ':library')
81 | androidxImplementation androidXLibraries.appCompat
82 | androidxImplementation androidXLibraries.constraintLayout
83 | supportImplementation supportLibraries.appCompat
84 | supportImplementation supportLibraries.constraintLayout
85 | materialImplementation libraries.material
86 | materialImplementation androidXLibraries.constraintLayout
87 | testImplementation testLibraries.junit4
88 | testImplementation testLibraries.robolectric
89 | testImplementation testLibraries.androidXRunner
90 | testImplementation testLibraries.androidXEspressoCore
91 | testImplementation testLibraries.androidXEspressoRules
92 | testImplementation testLibraries.supportRunner
93 | testImplementation testLibraries.supportEspressoCore
94 | testImplementation testLibraries.supportEspressoRules
95 | }
96 |
--------------------------------------------------------------------------------
/kotlinApp/lint.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/kotlinApp/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/kotlinApp/src/androidTest/java/com/stylingandroid/rialto/MainActivityScreen.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | //class MainActivityScreen : Screen() {
4 | // val formattedTextView = KRialtoTextView { withId(R.id.formatted_text_view) }
5 | // val formattedEditText = KEditText { withId(R.id.formatted_edit_text) }
6 | // val unformattedTextView = KTextView { withId(R.id.unformatted_text_view) }
7 | // val unformattedEditText = KEditText { withId(R.id.unformatted_edit_text) }
8 | //}
9 | //
10 | //class KRialtoTextView : KBaseView, TextViewAssertions {
11 | // constructor(function: ViewBuilder.() -> Unit) : super(function)
12 | // constructor(parent: Matcher, function: ViewBuilder.() -> Unit) : super(parent, function)
13 | // constructor(parent: androidx.test.espresso.DataInteraction, function: ViewBuilder.() -> Unit) : super(parent, function)
14 | //
15 | // fun containsSpanAt(start: Int, end: Int, matcher: Matcher<*>) {
16 | // view.check(androidx.test.espresso.assertion.ViewAssertions.matches(TextViewMatcher(SpanMatcher(start, end, matcher))))
17 | // }
18 | //
19 | // fun containsStyleAt(start: Int, end: Int, style: Int) {
20 | // containsSpanAt(start, end, styleMatcher(style))
21 | // }
22 | //}
23 | //
24 | //class SpanMatcher(val start: Int, val end: Int, private val matcher: Matcher<*>) : BaseMatcher() {
25 | // override fun describeTo(description: Description?) {
26 | // description?.appendText("Span Matcher: ")
27 | // matcher.describeTo(description)
28 | // }
29 | //
30 | // override fun matches(item: Any?): Boolean = matcher.matches(item)
31 | //}
32 | //
33 | //class TextViewMatcher(private val matcher: SpanMatcher) : androidx.test.espresso.matcher.BoundedMatcher(TextView::class.java) {
34 | // override fun describeTo(description: Description?) {
35 | // description?.appendText("TextViewMatcher: ")
36 | // matcher.describeTo(description)
37 | // }
38 | //
39 | // override fun describeMismatch(item: Any?, description: Description?) {
40 | // when (item) {
41 | // is TextView -> {
42 | //// ((item.text as? SpannedString)?.run {
43 | //// getSpans(0, length, Any::class.java).forEach { span ->
44 | //// if (span)
45 | //// }
46 | //// }
47 | // }
48 | // null -> description?.appendText("Expected a TextView but got ")
49 | // else -> description?.appendText("Expected a TextView but got a ${item.javaClass.simpleName}")
50 | // }
51 | // }
52 | //
53 | // override fun matchesSafely(item: TextView?): Boolean {
54 | // (item?.text as? SpannedString)?.run {
55 | // getSpans(0, length, Any::class.java).forEach { span ->
56 | // if (getSpanStart(span) == matcher.start && getSpanEnd(span) == matcher.end && matcher.matches(span)) {
57 | // return true
58 | // }
59 | // }
60 | // }
61 | // return false
62 | // }
63 | //}
64 | //
65 | //fun styleMatcher(requiredStyle: Int): Matcher = object : BaseMatcher() {
66 | // override fun describeTo(description: Description?) {
67 | // description?.appendText("StyleMatcher!")
68 | // }
69 | //
70 | // override fun matches(item: Any?): Boolean {
71 | // return (item as? StyleSpan)?.run {
72 | // style == requiredStyle
73 | // } ?: false
74 | // }
75 | //
76 | //}
77 |
--------------------------------------------------------------------------------
/kotlinApp/src/androidTest/java/com/stylingandroid/rialto/MainActivityTest.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | //@RunWith(AndroidJUnit4::class)
4 | //class MainActivityTest {
5 | //
6 | // @get:Rule
7 | // val rule = ActivityTestRule(MainActivity::class.java)
8 | //
9 | // val screen = MainActivityScreen()
10 | //
11 | // @Test
12 | // fun test() {
13 | // screen {
14 | // formattedTextView {
15 | // //containsStyleAt(3, 5, Typeface.BOLD)
16 | // }
17 | // }
18 | // }
19 | //}
20 |
--------------------------------------------------------------------------------
/kotlinApp/src/androidx/java/com/stylingandroid/rialto/app/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.graphics.Typeface
4 | import android.os.Bundle
5 | import android.text.style.StyleSpan
6 | import android.text.style.UnderlineSpan
7 | import com.stylingandroid.rialto.format.getFormattedText
8 | import kotlinx.android.synthetic.androidx.activity_main.*
9 |
10 | class MainActivity : RialtoActivity() {
11 |
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
15 | registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
16 | registerSpanFactory("format", "bold_underline") { StyleSpan(Typeface.BOLD) }
17 | registerSpanFactory("format", "bold_underline") { UnderlineSpan() }
18 | setContentView(R.layout.activity_main)
19 |
20 | format_string.text = resources.getFormattedText(R.string.formatted_italic, "formatted")
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/kotlinApp/src/androidx/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
31 |
32 |
44 |
45 |
58 |
59 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/ic_launcher-web.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/java/com/stylingandroid/rialto/app/KotlinApplication.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.app.Application
4 | import android.text.style.UnderlineSpan
5 | import com.stylingandroid.rialto.Registry
6 | import com.stylingandroid.rialto.RialtoRegistry
7 | import com.stylingandroid.rialto.font.FontRegistrar
8 |
9 | class KotlinApplication @JvmOverloads constructor(
10 | registry: RialtoRegistry = Registry()
11 | ) : Application(), RialtoRegistry by registry {
12 |
13 | override fun onCreate() {
14 | super.onCreate()
15 | registerSpanFactory("format", "underline") { UnderlineSpan() }
16 | FontRegistrar(this).registerFonts(this, "font", R.array.preloaded_fonts)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
32 |
33 |
34 |
35 |
36 |
37 |
41 |
45 |
46 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
17 |
24 |
31 |
38 |
45 |
52 |
59 |
66 |
73 |
80 |
87 |
94 |
101 |
108 |
115 |
116 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/StylingAndroid/Rialto/cd86cc260aa84e03816ab0566fdd3892bdaf489f/kotlinApp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #1E9618
4 | #4EE147
5 | #156912
6 |
7 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Rialto
3 |
4 |
--------------------------------------------------------------------------------
/kotlinApp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/kotlinApp/src/material/java/com/stylingandroid/rialto/app/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.graphics.Typeface
4 | import android.os.Bundle
5 | import android.text.style.StyleSpan
6 | import android.text.style.UnderlineSpan
7 | import androidx.appcompat.app.AppCompatActivity
8 | import com.stylingandroid.rialto.FactorySet
9 | import com.stylingandroid.rialto.RialtoDelegate
10 | import com.stylingandroid.rialto.RialtoDelegateImpl
11 | import com.stylingandroid.rialto.RialtoRegistry
12 | import com.stylingandroid.rialto.format.getFormattedText
13 | import kotlinx.android.synthetic.material.activity_main.*
14 |
15 | class MainActivity : AppCompatActivity(), RialtoDelegate {
16 | private lateinit var delegate: RialtoDelegate
17 |
18 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
19 | delegate.registerSpanFactory(key, value, creator)
20 | }
21 |
22 | override fun processAnnotations(text: CharSequence?): CharSequence? =
23 | delegate.processAnnotations(text)
24 |
25 | override fun get(key: String, value: String): FactorySet = delegate.get(key, value)
26 |
27 | override fun copy(): RialtoRegistry = delegate.copy()
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | delegate = RialtoDelegateImpl(this)
31 |
32 | super.onCreate(savedInstanceState)
33 | registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
34 | registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
35 | registerSpanFactory("format", "bold_underline") { StyleSpan(Typeface.BOLD) }
36 | registerSpanFactory("format", "bold_underline") { UnderlineSpan() }
37 | setContentView(R.layout.activity_main)
38 |
39 | format_string.text = resources.getFormattedText(R.string.formatted_italic, "formatted")
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/kotlinApp/src/material/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
20 |
21 |
32 |
33 |
45 |
46 |
59 |
60 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/kotlinApp/src/material/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/kotlinApp/src/support/java/com/stylingandroid/rialto/app/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.graphics.Typeface
4 | import android.os.Bundle
5 | import android.text.style.StyleSpan
6 | import android.text.style.UnderlineSpan
7 | import com.stylingandroid.rialto.format.getFormattedText
8 | import kotlinx.android.synthetic.support.activity_main.*
9 |
10 | class MainActivity : RialtoActivity() {
11 |
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
15 | registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
16 | registerSpanFactory("format", "bold_underline") { StyleSpan(Typeface.BOLD) }
17 | registerSpanFactory("format", "bold_underline") { UnderlineSpan() }
18 | setContentView(R.layout.activity_main)
19 |
20 | format_string.text = resources.getFormattedText(R.string.formatted_italic, "formatted")
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/kotlinApp/src/support/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
31 |
32 |
44 |
45 |
58 |
59 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "io.gitlab.arturbosch.detekt" version "1.0.0-RC11"
3 | id "com.jfrog.bintray" version "1.8.4" // Enables publishing to bintray
4 | id "com.github.dcendents.android-maven" version "1.5" // Allows aar in mavenPublications
5 | }
6 |
7 | apply plugin: 'com.android.library'
8 | apply plugin: 'kotlin-android-extensions'
9 | apply plugin: 'kotlin-android'
10 | apply plugin: 'maven-publish' // Used for mavenPublications
11 |
12 | android {
13 | compileSdkVersion androidCompileSdkVersion
14 |
15 | defaultConfig {
16 | minSdkVersion androidMinSdkVersion
17 | targetSdkVersion androidTargetSdkVersion
18 | versionCode libraryCode
19 | versionName libraryVersion
20 |
21 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
22 |
23 | }
24 |
25 | buildTypes {
26 | release {
27 | minifyEnabled false
28 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
29 | }
30 | }
31 |
32 | flavorDimensions "libtype"
33 |
34 | productFlavors {
35 | support {
36 | dimension "libtype"
37 | }
38 | androidx {
39 | dimension "libtype"
40 | }
41 | material {
42 | dimension "libtype"
43 | }
44 | }
45 | sourceSets {
46 | androidx {
47 | java.srcDirs += 'src/commonx/java'
48 | res.srcDirs += 'src/commonx/res'
49 | }
50 | material {
51 | java.srcDirs +='src/commonx/java'
52 | res.srcDirs += 'src/commonx/res'
53 | }
54 | }
55 | testOptions {
56 | //unitTests.returnDefaultValues = true
57 | unitTests.includeAndroidResources = true
58 | }
59 | }
60 |
61 | detekt {
62 | version = "1.0.0-RC11"
63 | input = files("src/main/java", "src/commonx/java", "src/androidx/java", "src/material/java", "src/support/java")
64 | filters = ".*test.*,.*/resources/.*,.*/tmp/.*"
65 | }
66 |
67 | dependencies {
68 | implementation libraries.kotlinStdLib
69 | implementation libraries.kotlinCoroutinesCore
70 | implementation libraries.kotlinCoroutinesAndroid
71 |
72 | androidxImplementation androidXLibraries.appCompat
73 | supportImplementation supportLibraries.appCompat
74 | materialImplementation 'com.google.android.material:material:1.0.0'
75 |
76 | testImplementation testLibraries.junit4
77 | testImplementation testLibraries.mockitoCore
78 | testImplementation testLibraries.kotlinTestJunit
79 | testImplementation testLibraries.mockitoKotlin
80 | testImplementation testLibraries.robolectric
81 | }
82 |
83 | apply from: '../publish.gradle' // Makes this library publishable
84 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/library/src/androidx/java/androidx/appcompat/app/RialtoViewInflater.kt:
--------------------------------------------------------------------------------
1 | package androidx.appcompat.app
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import androidx.appcompat.widget.AppCompatEditText
6 | import androidx.appcompat.widget.AppCompatTextView
7 | import com.stylingandroid.rialto.androidx.widget.RialtoEditText
8 | import com.stylingandroid.rialto.androidx.widget.RialtoTextView
9 |
10 | internal class RialtoViewInflater : AppCompatViewInflater() {
11 |
12 | override fun createTextView(context: Context, attrs: AttributeSet?): AppCompatTextView {
13 | return RialtoTextView(context, attrs)
14 | }
15 |
16 | override fun createEditText(context: Context, attrs: AttributeSet?): AppCompatEditText {
17 | return RialtoEditText(context, attrs)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/library/src/commonx/java/androidx/appcompat/app/ViewFactory.kt:
--------------------------------------------------------------------------------
1 | package androidx.appcompat.app
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import com.stylingandroid.rialto.androidx.widget.RialtoEditText
8 | import com.stylingandroid.rialto.androidx.widget.RialtoTextView
9 |
10 | internal class ViewFactory private constructor(
11 | private val viewInflater: RialtoViewInflater,
12 | private val contextProvider: (context: Context) -> Context
13 | ) : LayoutInflater.Factory2 {
14 |
15 | constructor(
16 | contextProvider: (context: Context) -> Context
17 | ) : this(RialtoViewInflater(), contextProvider)
18 |
19 | override fun onCreateView(parent: View?, name: String?, context: Context, attrs: AttributeSet): View? =
20 | viewInflater.createView(parent, name, contextProvider(context), attrs, false, true, true, true).also {
21 | (it as? RialtoTextView)?.initialiseDelegate()
22 | (it as? RialtoEditText)?.initialiseDelegate()
23 | }
24 |
25 | override fun onCreateView(name: String?, context: Context, attrs: AttributeSet): View? =
26 | onCreateView(null, name, context, attrs)
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/library/src/commonx/java/com/stylingandroid/rialto/RialtoDelegateImpl.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import androidx.appcompat.app.AppCompatActivity
4 | import androidx.appcompat.app.ViewFactory
5 | import androidx.core.view.LayoutInflaterCompat
6 |
7 | class RialtoDelegateImpl(activity: AppCompatActivity) : RialtoBaseDelegate(
8 | (activity.application as? RialtoRegistry) ?: Registry()
9 | ) {
10 |
11 | init {
12 | LayoutInflaterCompat.setFactory2(activity.layoutInflater, ViewFactory { context ->
13 | RialtoFactoryContext(context, this)
14 | })
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/library/src/commonx/java/com/stylingandroid/rialto/androidx/widget/RialtoEditText.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.androidx.widget
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.widget.TextView
6 | import androidx.appcompat.R
7 | import androidx.appcompat.widget.AppCompatEditText
8 | import com.stylingandroid.rialto.RialtoTextDelegate
9 | import com.stylingandroid.rialto.TextViewDelegate
10 |
11 | class RialtoEditText @JvmOverloads constructor(
12 | context: Context,
13 | private val attrs: AttributeSet? = null,
14 | defaultStyle: Int = R.attr.editTextStyle
15 | ) : AppCompatEditText(context, attrs, defaultStyle) {
16 |
17 | private lateinit var delegate: RialtoTextDelegate
18 |
19 | private var deferredText: Pair? = null
20 |
21 | var doFormatting: Boolean
22 | get() = delegate.doFormatting
23 | set(value) {
24 | delegate.doFormatting = value
25 | }
26 |
27 | fun initialiseDelegate() {
28 | attrs?.also {
29 | delegate = TextViewDelegate(context, it, this)
30 | deferredText?.also { (text, type) ->
31 | setText(text, type)
32 | }
33 | deferredText = null
34 | }
35 | }
36 |
37 | override fun setText(text: CharSequence?, type: TextView.BufferType?) {
38 | /*
39 | * setText() will be called from the base class constructor, so we need to defer
40 | * actually setting the text until we have created the Delegate
41 | */
42 | if (::delegate.isInitialized) {
43 | delegate.setText(text, type) { newText, newType ->
44 | super.setText(newText, newType)
45 | }
46 | } else {
47 | if (text != null && type != null) {
48 | super.setText(text, type)
49 | deferredText = text to type
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/library/src/commonx/java/com/stylingandroid/rialto/androidx/widget/RialtoTextView.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.androidx.widget
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.widget.TextView
6 | import androidx.appcompat.widget.AppCompatTextView
7 | import com.stylingandroid.rialto.TextViewDelegate
8 |
9 | class RialtoTextView @JvmOverloads constructor(
10 | context: Context,
11 | private val attrs: AttributeSet? = null,
12 | defaultStyle: Int = 0
13 | ) : AppCompatTextView(context, attrs, defaultStyle) {
14 |
15 | private lateinit var delegate: TextViewDelegate
16 |
17 | private var deferredText: Pair? = null
18 |
19 | var doFormatting: Boolean
20 | get() = delegate.doFormatting
21 | set(value) {
22 | delegate.doFormatting = value
23 | }
24 |
25 | fun initialiseDelegate() {
26 | attrs?.also {
27 | delegate = TextViewDelegate(context, it, this)
28 | deferredText?.also { (text, type) ->
29 | setText(text, type)
30 | }
31 | deferredText = null
32 | }
33 | }
34 |
35 | override fun setText(text: CharSequence?, type: TextView.BufferType?) {
36 | /*
37 | * setText() will be called from the base class constructor, so we need to defer
38 | * actually setting the text until we have created the Delegate
39 | */
40 | if (::delegate.isInitialized) {
41 | delegate.setText(text, type) { newText, newType ->
42 | super.setText(newText, newType)
43 | }
44 | } else {
45 | if (text != null && type != null) {
46 | super.setText(text, type)
47 | deferredText = text to type
48 | }
49 | }
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/library/src/commonx/java/com/stylingandroid/rialto/app/RialtoActivity.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import androidx.lifecycle.LifecycleOwner
6 | import com.stylingandroid.rialto.FactorySet
7 | import com.stylingandroid.rialto.RialtoDelegate
8 | import com.stylingandroid.rialto.RialtoDelegateImpl
9 | import com.stylingandroid.rialto.RialtoRegistry
10 |
11 | open class RialtoActivity : AppCompatActivity(), RialtoDelegate, LifecycleOwner {
12 |
13 | private lateinit var delegate: RialtoDelegate
14 |
15 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
16 | delegate.registerSpanFactory(key, value, creator)
17 | }
18 |
19 | override fun processAnnotations(text: CharSequence?): CharSequence? =
20 | delegate.processAnnotations(text)
21 |
22 | override fun get(key: String, value: String): FactorySet = delegate.get(key, value)
23 |
24 | override fun copy(): RialtoRegistry = delegate.copy()
25 |
26 | override fun onCreate(savedInstanceState: Bundle?) {
27 | delegate = RialtoDelegateImpl(this)
28 | super.onCreate(savedInstanceState)
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/library/src/commonx/java/com/stylingandroid/rialto/font/FontRegistrar.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.font
2 |
3 | import android.content.Context
4 | import android.content.res.Resources
5 | import androidx.annotation.ArrayRes
6 | import androidx.core.content.res.ResourcesCompat
7 | import com.stylingandroid.rialto.RialtoRegistry
8 |
9 | class FontRegistrar @JvmOverloads constructor(
10 | private val context: Context,
11 | private val resources: Resources = context.resources
12 | ) {
13 |
14 | fun registerFonts(registry: RialtoRegistry, key: String, @ArrayRes preloadedFonts: Int) {
15 | resources.getStringArray(preloadedFonts)
16 | .map { it.removePrefix("res/font/").removeSuffix(".xml") }
17 | .forEach { fontName ->
18 | try {
19 | ResourcesCompat.getFont(
20 | context,
21 | resources.getIdentifier(fontName, "font", context.packageName)
22 | )
23 | } catch (e: Resources.NotFoundException) {
24 | null
25 | }?.also { typeface ->
26 | registry.registerSpanFactory(key, fontName) {
27 | CustomTypefaceSpan(typeface)
28 | }
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/Registry.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | typealias Factory = () -> Any
4 | typealias FactorySet = Set
5 |
6 | class Registry constructor(
7 | private val collection: MutableMap>> = mutableMapOf()
8 | ) : RialtoRegistry {
9 |
10 | constructor(
11 | parent: Registry,
12 | collection: MutableMap>> = mutableMapOf()
13 | ) : this(collection) {
14 | collection.putAll(parent.collection)
15 | }
16 |
17 | private val emptyValueMap = emptyMap()
18 | private val emptyFactorySet = emptySet()
19 |
20 | override operator fun get(key: String, value: String) : FactorySet =
21 | (collection[key.toLowerCase()] ?: emptyValueMap)[value.toLowerCase()] ?: emptyFactorySet
22 |
23 |
24 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
25 | (collection[key.toLowerCase()] ?: let {
26 | mutableMapOf>().also { values ->
27 | collection[key.toLowerCase()] = values
28 | }
29 | }).registerFactory(value, creator)
30 | }
31 |
32 | private fun MutableMap>.registerFactory(value: String, factory: () -> Any) {
33 | (this[value.toLowerCase()] ?: let {
34 | mutableSetOf<() -> Any>().also { factories ->
35 | this[value.toLowerCase()] = factories
36 | }
37 | }).registerFactory(factory)
38 | }
39 |
40 | private fun MutableSet.registerFactory(factory: () -> Any) {
41 | add(factory)
42 | }
43 |
44 | override fun copy(): RialtoRegistry =
45 | Registry(collection.toMutableMap())
46 | }
47 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/RialtoBaseDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.text.Annotation
4 | import android.text.SpannableStringBuilder
5 | import android.text.Spanned
6 |
7 | open class RialtoBaseDelegate(private val registry: RialtoRegistry) : RialtoDelegate, RialtoRegistry by registry {
8 |
9 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
10 | registry.registerSpanFactory(key, value, creator)
11 | }
12 |
13 | override fun processAnnotations(text: CharSequence?): CharSequence? {
14 | return if (text is Spanned) {
15 | processAnnotations(text, SpannableStringBuilder(text))
16 | } else {
17 | text
18 | }
19 | }
20 |
21 | internal fun processAnnotations(
22 | spannedString: Spanned,
23 | spannableStringBuilder: SpannableStringBuilder
24 | ): CharSequence {
25 | spannedString.getSpans(0, spannedString.length, Annotation::class.java)
26 | .forEach { annotation ->
27 | annotation.applySpan(
28 | spannedString.getSpanStart(annotation),
29 | spannedString.getSpanEnd(annotation),
30 | spannableStringBuilder
31 | )
32 | }
33 | return spannableStringBuilder
34 | }
35 |
36 | private fun Annotation.applySpan(start: Int, end: Int, spannableStringBuilder: SpannableStringBuilder) =
37 | registry[key, value].forEach { factory ->
38 | spannableStringBuilder.setSpan(factory.invoke(), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/RialtoDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | /**
4 | * RialtoDelegate is the public facing interface of Rialto and has different implementations for
5 | * different support library configurations.
6 | */
7 | interface RialtoDelegate : RialtoRegistry {
8 |
9 | /**
10 | * Processes the given CharSequence adding registered spans wherever there are
11 | * annotations matching the registered key / value pair in the source CharSequence
12 | *
13 | * @property text The input CharSequence
14 | * @return The input with any matching spans added. This may be the same as input if no
15 | * matching annotations were found, or if input is not a SpannedString
16 | */
17 | fun processAnnotations(text: CharSequence?): CharSequence?
18 | }
19 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/RialtoFactoryContext.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.content.Context
4 | import android.content.ContextWrapper
5 |
6 | internal class RialtoFactoryContext(
7 | base: Context,
8 | private val registry: RialtoRegistry
9 | ) : ContextWrapper(base), RialtoRegistry by registry {
10 |
11 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
12 | registry.registerSpanFactory(key, value, creator)
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/RialtoRegistry.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | interface RialtoRegistry {
4 |
5 | operator fun get(key: String, value: String): FactorySet
6 |
7 | /**
8 | * Registers a span factory with a given annotation key / value pair
9 | *
10 | * @property key The annotation key to register the creator with
11 | * @property value The annotation value to register the creator with
12 | * @property creator A lambda which will be invoked to create new instances of the required span
13 | */
14 | fun registerSpanFactory(key: String, value: String, creator: () -> Any)
15 |
16 | fun copy(): RialtoRegistry
17 | }
18 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/RialtoTextDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.widget.TextView
4 |
5 | interface RialtoTextDelegate {
6 |
7 | fun setText(
8 | text: CharSequence?,
9 | type: TextView.BufferType?,
10 | setter: (text: CharSequence?, type: TextView.BufferType?) -> Unit
11 | )
12 |
13 | var doFormatting: Boolean
14 | }
15 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/TextViewDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.content.Context
4 | import android.content.ContextWrapper
5 | import android.util.AttributeSet
6 | import android.widget.TextView
7 |
8 | internal class TextViewDelegate(
9 | context: Context,
10 | attrs: AttributeSet,
11 | private val textView: TextView,
12 | override var doFormatting: Boolean = true
13 | ) : RialtoTextDelegate {
14 |
15 | init {
16 | doFormatting =
17 | context.theme.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0).let { ta ->
18 | try {
19 | ta.getBoolean(R.styleable.TextView_annotationFormatting, true)
20 | } finally {
21 | ta.recycle()
22 | }
23 | }
24 | }
25 |
26 | private val delegate: RialtoDelegate? = textView.context.findFactoryProvider()
27 |
28 | private fun Context.findFactoryProvider(): RialtoDelegate? {
29 | return when (this) {
30 | is RialtoDelegate -> this
31 | is ContextWrapper -> baseContext.findFactoryProvider()
32 | else -> null
33 | }
34 | }
35 |
36 | override fun setText(
37 | text: CharSequence?,
38 | type: TextView.BufferType?,
39 | setter: (CharSequence?, TextView.BufferType?) -> Unit) {
40 | if (textView.text?.isEmpty() == true && text?.isNotEmpty() == true) {
41 | setter(text, type)
42 | }
43 |
44 | if (doFormatting) {
45 | delegate?.processAnnotations(text)?.also { processedText ->
46 | setter(processedText, type)
47 | }
48 |
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/app/RialtoApplication.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.app.Application
4 | import com.stylingandroid.rialto.Registry
5 | import com.stylingandroid.rialto.RialtoRegistry
6 |
7 | class RialtoApplication @JvmOverloads constructor(
8 | registry: RialtoRegistry = Registry()
9 | ) : Application(), RialtoRegistry by registry
10 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/font/CustomTypefaceSpan.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.font
2 |
3 | import android.graphics.Typeface
4 | import android.text.TextPaint
5 | import android.text.style.MetricAffectingSpan
6 |
7 | class CustomTypefaceSpan(private val font: Typeface?) : MetricAffectingSpan() {
8 |
9 | override fun updateMeasureState(textPaint: TextPaint) = update(textPaint)
10 |
11 | override fun updateDrawState(textPaint: TextPaint) = update(textPaint)
12 |
13 | private fun update(textPaint: TextPaint) {
14 | textPaint.typeface = Typeface.create(font, textPaint.typeface?.style ?: 0)
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/library/src/main/java/com/stylingandroid/rialto/format/SpannableFormatter.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.format
2 |
3 | import android.content.res.Resources
4 | import android.text.SpannableStringBuilder
5 | import android.text.SpannedString
6 | import java.util.regex.Pattern
7 |
8 | fun Resources.getFormattedText(id: Int, vararg formatArgs: Any): CharSequence {
9 | val text = getText(id)
10 | return if (text is SpannedString) {
11 | @Suppress("SpreadOperator") // really need to use the spread operator here for Java interoperability
12 | SpannableFormatter().format(text, *formatArgs)
13 | } else text
14 | }
15 |
16 | class SpannableFormatter {
17 | private val index = "(\\d+\\\$)"
18 | private val width = "(\\d+)?"
19 | private val precision = "(\\.\\d+)?"
20 | private val general = "(-)?($width[bBhHsScC])"
21 | private val character = "(-)?($width[cC])"
22 | private val decimal = "(([-+ 0,(]*)?${width}d)"
23 | private val integral = "(([-#+ 0(]*)?$width[oxX])"
24 | private val floatingPoint = "(([-#+ 0(]*)?$width$precision[eEfgG])"
25 | private val floatingPointHex = "(([-#+ ]*)?$width$precision[aA])"
26 | private val dateTime = "(([-]*)?$width[tT][HIklMSLNpzZsQBbhAaCYyjmdeRTrDFc])"
27 | private val percent = "(-?$width%)"
28 | private val lineSeparator = "(n)"
29 | internal val pattern = Pattern.compile(
30 | @Suppress("MaxLineLength")
31 | "%$index($general|$character|$decimal|$integral|$floatingPoint|$floatingPointHex|$dateTime|$percent|$lineSeparator)"
32 | )
33 |
34 | fun format(spanned: SpannedString, vararg formatArgs: Any?): CharSequence {
35 | val builder = SpannableStringBuilder(spanned)
36 | pattern.matcher(builder).apply {
37 | while (find()) {
38 | @Suppress("SpreadOperator") // really need to use the spread operator here for Java interoperability
39 | String.format(builder.substring(start() until end()), *formatArgs)
40 | .also { replacement ->
41 | builder.replace(start(), end(), replacement)
42 | }
43 | reset(builder)
44 | }
45 | }
46 | return builder
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/library/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/library/src/material/java/androidx/appcompat/app/RialtoViewInflater.kt:
--------------------------------------------------------------------------------
1 | package androidx.appcompat.app
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import androidx.appcompat.widget.AppCompatButton
6 | import androidx.appcompat.widget.AppCompatEditText
7 | import androidx.appcompat.widget.AppCompatTextView
8 | import com.google.android.material.button.MaterialButton
9 | import com.stylingandroid.rialto.androidx.widget.RialtoEditText
10 | import com.stylingandroid.rialto.androidx.widget.RialtoTextView
11 |
12 | internal class RialtoViewInflater : AppCompatViewInflater() {
13 |
14 | override fun createTextView(context: Context, attrs: AttributeSet?): AppCompatTextView {
15 | return RialtoTextView(context, attrs)
16 | }
17 |
18 | override fun createEditText(context: Context, attrs: AttributeSet?): AppCompatEditText {
19 | return RialtoEditText(context, attrs)
20 | }
21 |
22 | override fun createButton(context: Context, attrs: AttributeSet): AppCompatButton {
23 | return MaterialButton(context, attrs)
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/material/java/com/stylingandroid/rialto/material/widget/RialtoTextInputEditText.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.material.widget
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.widget.TextView
6 | import com.google.android.material.textfield.TextInputEditText
7 | import com.stylingandroid.rialto.RialtoTextDelegate
8 | import com.stylingandroid.rialto.TextViewDelegate
9 | import kotlinx.coroutines.CoroutineScope
10 |
11 | class RialtoTextInputEditText @JvmOverloads constructor(
12 | context: Context,
13 | private val attrs: AttributeSet? = null,
14 | defaultStyle: Int = 0
15 | ) : TextInputEditText(context, attrs, defaultStyle) {
16 | private lateinit var delegate: RialtoTextDelegate
17 |
18 | private var deferredText: Pair? = null
19 |
20 | var doFormatting: Boolean
21 | get() = delegate.doFormatting
22 | set(value) {
23 | delegate.doFormatting = value
24 | }
25 |
26 | private fun initialiseDelegate() {
27 | attrs?.also {
28 | delegate = TextViewDelegate(context, it, this)
29 | deferredText?.also { (text, type) ->
30 | setText(text, type)
31 | }
32 | deferredText = null
33 | }
34 | }
35 |
36 | override fun setText(text: CharSequence?, type: TextView.BufferType?) {
37 | /*
38 | * setText() will be called from the base class constructor, so we need to defer
39 | * actually setting the text until we have created the Delegate
40 | */
41 | if (::delegate.isInitialized) {
42 | delegate.setText(text, type) { newText, newType ->
43 | super.setText(newText, newType)
44 | }
45 | } else {
46 | if (text != null && type != null) {
47 | deferredText = text to type
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/library/src/support/java/android/support/v7/app/RialtoViewInflater.kt:
--------------------------------------------------------------------------------
1 | package android.support.v7.app
2 |
3 | import android.content.Context
4 | import android.support.v7.widget.AppCompatEditText
5 | import android.support.v7.widget.AppCompatTextView
6 | import android.util.AttributeSet
7 | import com.stylingandroid.rialto.support.widget.RialtoEditText
8 | import com.stylingandroid.rialto.support.widget.RialtoTextView
9 |
10 | internal class RialtoViewInflater : AppCompatViewInflater() {
11 |
12 | override fun createTextView(context: Context, attrs: AttributeSet?): AppCompatTextView {
13 | return RialtoTextView(context, attrs)
14 | }
15 |
16 | override fun createEditText(context: Context, attrs: AttributeSet?): AppCompatEditText {
17 | return RialtoEditText(context, attrs)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/library/src/support/java/android/support/v7/app/ViewFactory.kt:
--------------------------------------------------------------------------------
1 | package android.support.v7.app
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import com.stylingandroid.rialto.support.widget.RialtoEditText
8 | import com.stylingandroid.rialto.support.widget.RialtoTextView
9 |
10 | internal class ViewFactory private constructor(
11 | private val viewInflater: RialtoViewInflater,
12 | private val contextProvider: (context: Context) -> Context
13 | ) : LayoutInflater.Factory2 {
14 |
15 | constructor(
16 | contextProvider: (context: Context) -> Context
17 | ) : this(RialtoViewInflater(), contextProvider)
18 |
19 | override fun onCreateView(parent: View?, name: String?, context: Context, attrs: AttributeSet): View? =
20 | viewInflater.createView(parent, name, contextProvider(context), attrs, false, true, true, true).also {
21 | (it as? RialtoTextView)?.initialiseDelegate()
22 | (it as? RialtoEditText)?.initialiseDelegate()
23 | }
24 |
25 | override fun onCreateView(name: String?, context: Context, attrs: AttributeSet): View? =
26 | onCreateView(null, name, context, attrs)
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/library/src/support/java/com/stylingandroid/rialto/RialtoDelegateImpl.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.support.v4.view.LayoutInflaterCompat
4 | import android.support.v7.app.AppCompatActivity
5 | import android.support.v7.app.ViewFactory
6 |
7 | class RialtoDelegateImpl(activity: AppCompatActivity) : RialtoBaseDelegate(
8 | (activity.application as? RialtoRegistry) ?: Registry()
9 | ) {
10 |
11 | init {
12 | LayoutInflaterCompat.setFactory2(activity.layoutInflater, ViewFactory { context ->
13 | RialtoFactoryContext(context, this)
14 | })
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/library/src/support/java/com/stylingandroid/rialto/app/RialtoActivity.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.app
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 | import com.stylingandroid.rialto.FactorySet
6 | import com.stylingandroid.rialto.RialtoDelegate
7 | import com.stylingandroid.rialto.RialtoDelegateImpl
8 | import com.stylingandroid.rialto.RialtoRegistry
9 |
10 | open class RialtoActivity : AppCompatActivity(), RialtoDelegate {
11 |
12 | private lateinit var delegate: RialtoDelegate
13 |
14 | override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
15 | delegate.registerSpanFactory(key, value, creator)
16 | }
17 |
18 | override fun processAnnotations(text: CharSequence?): CharSequence? =
19 | delegate.processAnnotations(text)
20 |
21 | override fun get(key: String, value: String): FactorySet = delegate.get(key, value)
22 |
23 | override fun copy(): RialtoRegistry = delegate.copy()
24 |
25 | override fun onCreate(savedInstanceState: Bundle?) {
26 | delegate = RialtoDelegateImpl(this)
27 |
28 | super.onCreate(savedInstanceState)
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/library/src/support/java/com/stylingandroid/rialto/font/FontRegistrar.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.font
2 |
3 | import android.content.Context
4 | import android.content.res.Resources
5 | import android.support.annotation.ArrayRes
6 | import android.support.v4.content.res.ResourcesCompat
7 | import com.stylingandroid.rialto.RialtoRegistry
8 |
9 | class FontRegistrar @JvmOverloads constructor(
10 | private val context: Context,
11 | private val resources: Resources = context.resources
12 | ) {
13 |
14 | fun registerFonts(registry: RialtoRegistry, key: String, @ArrayRes preloadedFonts: Int) {
15 | resources.getStringArray(preloadedFonts)
16 | .map { it.removePrefix("res/font/").removeSuffix(".xml") }
17 | .forEach { fontName ->
18 | try {
19 | ResourcesCompat.getFont(
20 | context,
21 | resources.getIdentifier(fontName, "font", context.packageName)
22 | )
23 | } catch (e: Resources.NotFoundException) {
24 | null
25 | }?.also { typeface ->
26 | registry.registerSpanFactory(key, fontName) {
27 | CustomTypefaceSpan(typeface)
28 | }
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/support/java/com/stylingandroid/rialto/support/widget/RialtoEditText.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.support.widget
2 |
3 | import android.content.Context
4 | import android.support.v7.appcompat.R
5 | import android.support.v7.widget.AppCompatEditText
6 | import android.util.AttributeSet
7 | import android.widget.TextView
8 | import com.stylingandroid.rialto.TextViewDelegate
9 |
10 | class RialtoEditText @JvmOverloads constructor(
11 | context: Context,
12 | private val attrs: AttributeSet? = null,
13 | defaultStyle: Int = R.attr.editTextStyle
14 | ) : AppCompatEditText(context, attrs, defaultStyle) {
15 |
16 | private lateinit var delegate: TextViewDelegate
17 |
18 | private var deferredText: Pair? = null
19 |
20 | var doFormatting: Boolean
21 | get() = delegate.doFormatting
22 | set(value) {
23 | delegate.doFormatting = value
24 | }
25 |
26 | fun initialiseDelegate() {
27 | attrs?.also {
28 | delegate = TextViewDelegate(context, it, this)
29 | deferredText?.also { (text, type) ->
30 | setText(text, type)
31 | }
32 | deferredText = null
33 | }
34 | }
35 |
36 | override fun setText(text: CharSequence?, type: TextView.BufferType?) {
37 | /*
38 | * setText() will be called from the base class constructor, so we need to defer
39 | * actually setting the text until we have created the Delegate
40 | */
41 | if (::delegate.isInitialized) {
42 | delegate.setText(text, type) { newText, newType ->
43 | super.setText(newText, newType)
44 | }
45 | } else {
46 | if (text != null && type != null) {
47 | super.setText(text, type)
48 | deferredText = text to type
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/library/src/support/java/com/stylingandroid/rialto/support/widget/RialtoTextView.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.support.widget
2 |
3 | import android.content.Context
4 | import android.support.v7.widget.AppCompatTextView
5 | import android.util.AttributeSet
6 | import android.widget.TextView
7 | import com.stylingandroid.rialto.TextViewDelegate
8 |
9 | class RialtoTextView @JvmOverloads constructor(
10 | context: Context,
11 | private val attrs: AttributeSet? = null,
12 | defaultStyle: Int = 0
13 | ) : AppCompatTextView(context, attrs, defaultStyle) {
14 |
15 | private lateinit var delegate: TextViewDelegate
16 |
17 | private var deferredText: Pair? = null
18 |
19 | var doFormatting: Boolean
20 | get() = delegate.doFormatting
21 | set(value) {
22 | delegate.doFormatting = value
23 | }
24 |
25 | fun initialiseDelegate() {
26 | attrs?.also {
27 | delegate = TextViewDelegate(context, it, this)
28 | deferredText?.also { (text, type) ->
29 | setText(text, type)
30 | }
31 | deferredText = null
32 | }
33 | }
34 |
35 | override fun setText(text: CharSequence?, type: TextView.BufferType?) {
36 | /*
37 | * setText() will be called from the base class constructor, so we need to defer
38 | * actually setting the text until we have created the Delegate
39 | */
40 | if (::delegate.isInitialized) {
41 | delegate.setText(text, type) { newText, newType ->
42 | super.setText(newText, newType)
43 | }
44 | } else {
45 | if (text != null && type != null) {
46 | super.setText(text, type)
47 | deferredText = text to type
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/library/src/test/java/com/stylingandroid/rialto/RegistryTest.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.text.style.CharacterStyle
4 | import com.nhaarman.mockitokotlin2.mock
5 | import org.junit.Test
6 | import kotlin.test.assertEquals
7 | import kotlin.test.assertSame
8 | import kotlin.test.assertTrue
9 |
10 | class RegistryTest {
11 |
12 | private lateinit var registryMap: MutableMap>>
13 | private lateinit var registry: Registry
14 | private val characterStyle1: CharacterStyle = mock()
15 | private val characterStyle2: CharacterStyle = mock()
16 |
17 | @Test
18 | fun `Given an empty registry When we don't register anything Then the backing collection is empty`() {
19 | createEmptyRegistry()
20 |
21 | assertTrue { registryMap.isEmpty() }
22 | }
23 |
24 | @Test
25 | fun `Given an empty registry When we register a single key value pair Then the backing collection has a single key item`() {
26 | createEmptyRegistry()
27 |
28 | registry.registerSpanFactory("key", "value") { characterStyle1 }
29 |
30 | assertEquals(1, registryMap.size)
31 | }
32 |
33 | @Test
34 | fun `Given an empty registry When we register a single key value pair Then the backing collection has a single value item`() {
35 | createEmptyRegistry()
36 |
37 | registry.registerSpanFactory("key", "value") { characterStyle1 }
38 |
39 | assertEquals(1, registry["key", "value"].size)
40 | }
41 |
42 | @Test
43 | fun `Given an empty registry When we register a single key value pair Then the backing collection has a single factory item`() {
44 | createEmptyRegistry()
45 |
46 | registry.registerSpanFactory("key", "value") { characterStyle1 }
47 |
48 | assertEquals(1, registry["key", "value"].size)
49 | }
50 |
51 | @Test
52 | fun `Given an empty registry When we register a the same key value pair multiple times Then the backing collection has a single key item`() {
53 | createEmptyRegistry()
54 |
55 | registry.registerSpanFactory("key", "value") { characterStyle1 }
56 | registry.registerSpanFactory("key", "value") { characterStyle2 }
57 |
58 | assertEquals(1, registryMap.size)
59 | }
60 |
61 | @Test
62 | fun `Given an empty registry When we register a the same key value pair multiple times Then the backing collection has a two value items`() {
63 | createEmptyRegistry()
64 |
65 | registry.registerSpanFactory("key", "value") { characterStyle1 }
66 | registry.registerSpanFactory("key", "value") { characterStyle2 }
67 |
68 | assertEquals(2, registry["key", "value"].size)
69 | }
70 |
71 | @Test
72 | fun `Given an empty registry When we register a the two key values Then the backing collection has a two value items`() {
73 | createEmptyRegistry()
74 |
75 | registry.registerSpanFactory("key", "value1") { characterStyle1 }
76 | registry.registerSpanFactory("key", "value2") { characterStyle1 }
77 |
78 | assertEquals(2, registryMap["key"]?.size)
79 | }
80 |
81 | @Test
82 | fun `Given an empty registry When we register a the two key values Then the backing collection has separate factory items`() {
83 | createEmptyRegistry()
84 |
85 | registry.registerSpanFactory("key", "value1") { characterStyle1 }
86 | registry.registerSpanFactory("key", "value2") { characterStyle1 }
87 |
88 | assertEquals(1, registry["key", "value1"].size)
89 | assertEquals(1, registry["key", "value2"].size)
90 | }
91 |
92 | @Test
93 | fun `Given an initialised parent registry When we clone it Then the backing collection has identical factory items`() {
94 | createEmptyRegistry()
95 | val factory: () -> Any = { characterStyle1 }
96 | registry.registerSpanFactory("key", "value1", factory)
97 |
98 | val child = Registry(registry)
99 |
100 | assertEquals(1, child["key", "value1"].size)
101 | assertSame(factory, registry["key", "value1"].first())
102 | }
103 |
104 | private fun createEmptyRegistry() {
105 | registryMap = mutableMapOf()
106 | registry = Registry(registryMap)
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/library/src/test/java/com/stylingandroid/rialto/RialtoFactoryTest.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto
2 |
3 | import android.text.Annotation
4 | import android.text.SpannableStringBuilder
5 | import android.text.SpannedString
6 | import android.text.style.CharacterStyle
7 | import com.nhaarman.mockitokotlin2.mock
8 | import com.nhaarman.mockitokotlin2.verify
9 | import com.nhaarman.mockitokotlin2.whenever
10 | import org.junit.Ignore
11 | import org.junit.Test
12 | import org.mockito.ArgumentMatchers.any
13 | import org.mockito.ArgumentMatchers.anyInt
14 | import kotlin.test.assertSame
15 |
16 | @Ignore
17 | class RialtoFactoryTest {
18 |
19 | private val characterStyle1: CharacterStyle = mock()
20 | private val spannedString: SpannedString = mock()
21 | private val annotation: Annotation = mock()
22 | private val spannableStringBuilder: SpannableStringBuilder = mock()
23 |
24 | @Test
25 | fun `Given an initialised factory When we match an annotation span Then setSpan is called on the builder`() {
26 | val delegate = RialtoBaseDelegate(Registry())
27 | delegate.registerSpanFactory("key", "value") { characterStyle1 }
28 | whenever(spannedString.getSpans(anyInt(), anyInt(), any(Class::class.java))).thenReturn(arrayOf(annotation))
29 | whenever(spannedString.getSpanStart(annotation)).thenReturn(4)
30 | whenever(spannedString.getSpanEnd(annotation)).thenReturn(6)
31 | whenever(annotation.key).thenReturn("key")
32 | whenever(annotation.value).thenReturn("value")
33 |
34 | delegate.processAnnotations(spannedString, spannableStringBuilder)
35 |
36 | verify(spannableStringBuilder).setSpan(characterStyle1, 4, 6, SpannedString.SPAN_EXCLUSIVE_EXCLUSIVE)
37 | }
38 |
39 | @Test
40 | fun `Given a String input When we call processAnnotations() Then the same object is returned`() {
41 | val delegate = RialtoBaseDelegate(Registry())
42 | delegate.registerSpanFactory("key", "value") { characterStyle1 }
43 | val string = "Hello World!"
44 |
45 | val result = delegate.processAnnotations(string)
46 |
47 | assertSame(string, result)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/library/src/test/java/com/stylingandroid/rialto/format/FormatterRegexTest.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.format
2 |
3 | import org.junit.Test
4 | import org.junit.runner.RunWith
5 | import org.junit.runners.Parameterized
6 | import java.util.regex.Matcher
7 | import kotlin.test.assertEquals
8 |
9 | @RunWith(Parameterized::class)
10 | class FormatterRegexTest(
11 | private val string: String,
12 | @Suppress("UNUSED_PARAMETER") description: String,
13 | private val expectedMatches: Int
14 | ) {
15 |
16 | private val formatter = SpannableFormatter()
17 |
18 | companion object {
19 |
20 | @JvmStatic
21 | @Parameterized.Parameters(name = "{1}: \"{0}\"")
22 | fun params() = listOf(
23 | arrayOf("Test", "No format", 0),
24 | arrayOf("%1\$s", "Format only", 1),
25 | arrayOf("%1\$s Text", "Format start", 1),
26 | arrayOf("Text %1\$s", "Format end", 1),
27 | arrayOf("%1\$s %2\$d", "Double with space", 2),
28 | arrayOf("%1\$s%2\$d", "Double no space", 2),
29 | arrayOf("%1\$s%1\$d", "Duplicate no space", 2),
30 | arrayOf("%1\$b %1\$-b %1\$B %1\$-B", "Boolean", 4),
31 | arrayOf("%1\$h %1\$-h %1\$H %1\$-H", "Hex", 4),
32 | arrayOf("%1\$s %1\$-s %1\$S %1\$-S %1\$8s %1\$-15s %1\$7S %1\$-1S", "String", 8),
33 | arrayOf("%1\$c %1\$-c %1\$C %1\$-C %1\$8c %1\$-15c %1\$7C %1\$-1C", "Char", 8),
34 | arrayOf("%1\$d %1\$-d %1\$8d %1\$-15d %1\$,7d %1\$-,1d %1\$(-1d", "Decimal", 7),
35 | arrayOf("%1\$o %1\$-o %1\$8o %1\$-15o %1\$+ 7o %1\$-+01o %1\$(-1o", "Octal", 7),
36 | arrayOf("%1\$x %1\$-X %1\$8x %1\$-15X %1\$+ 7x %1\$-+01X %1\$(-1x", "Hex", 7),
37 | arrayOf("%1\$e %1\$-E %1\$8e %1\$-15.4E %1\$+ 7.2e %1\$-+01E %1\$(-1e", "Scientific", 7),
38 | arrayOf("%1\$f %1\$-f %1\$8f %1\$-15.4f %1\$+ 7.2f %1\$-+01f %1\$(-1f %1\$(-1F", "Float", 7),
39 | arrayOf("%1\$g %1\$-G %1\$8g %1\$-15.4G %1\$+ 7.2g %1\$-+01G %1\$(-1g", "Scientific rounded", 7),
40 | arrayOf("%1\$a %1\$-A %1\$8a %1\$-15.4A %1\$+ 7.2a %1\$-+01A %1\$-1a", "Hex Float", 7),
41 | arrayOf("%1\$-tH %1\$TI %1\$-tk %1\$8tl %1\$-15tM %1\$7TS %1\$-1tL %1\$-1tN %1\$-1tp %1\$-1tz %1\$-1tZ %1\$-1ts %1\$-1tQ", "Time", 13),
42 | arrayOf("%1\$-tB %1\$Tb %1\$-th %1\$8tA %1\$-15ta %1\$7TC %1\$-1tY %1\$-1ty %1\$-1tj %1\$-1tm %1\$-1td %1\$-1te", "Date", 12),
43 | arrayOf("%1\$-tR %1\$TT %1\$-tr %1\$8tD %1\$-15tF %1\$7Tc", "Date/Time", 6),
44 | arrayOf("%1\$-t %1\$T", "Date / Time without qualifiers", 0),
45 | arrayOf("%1\$% %1\$-% %1\$-4%", "Percent", 3),
46 | arrayOf("%1\$n %1\$-n %1\$2n", "Line Separator", 1)
47 | )
48 | }
49 |
50 | @Test
51 | fun test() {
52 | val matches = formatter.pattern.matcher(string).findCount()
53 | assertEquals(expectedMatches, matches)
54 | }
55 |
56 | private fun Matcher.findCount(): Int {
57 | var count = 0
58 | while (find()) count++
59 | return count
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/library/src/test/java/com/stylingandroid/rialto/format/SpannableFormatterTest.kt:
--------------------------------------------------------------------------------
1 | package com.stylingandroid.rialto.format
2 |
3 | import android.graphics.Typeface
4 | import android.text.SpannableStringBuilder
5 | import android.text.Spanned
6 | import android.text.SpannedString
7 | import android.text.style.StyleSpan
8 | import android.text.style.UnderlineSpan
9 | import org.junit.Before
10 | import org.junit.Test
11 | import org.junit.runner.RunWith
12 | import org.robolectric.RobolectricTestRunner
13 | import kotlin.test.assertEquals
14 | import kotlin.test.assertNotNull
15 |
16 | @RunWith(RobolectricTestRunner::class)
17 | class SpannableFormatterTest {
18 |
19 | private val string1 = "String1"
20 | private val string2 = "String2"
21 |
22 | private val sourceString = "Test %1\$s and %2\$s."
23 |
24 | private lateinit var spanned: SpannedString
25 | private val expected = "Test $string1 and $string2."
26 |
27 | private val formatter = SpannableFormatter()
28 |
29 | @Before
30 | fun setup() {
31 | val source = SpannableStringBuilder(sourceString)
32 | source.setSpan(StyleSpan(Typeface.BOLD), 5, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
33 | source.setSpan(UnderlineSpan(), 10, 12, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
34 | spanned = SpannedString(source)
35 | }
36 |
37 | @Test
38 | fun `Given a string with format placeholders When we format it Then the correct result is produced`() {
39 | val actual = formatter.format(spanned, string1, string2)
40 |
41 | assertEquals(expected, actual.toString())
42 | }
43 |
44 | @Test
45 | fun `Given a string with a span around a format placeholder When we format it Then the span is still present`() {
46 | val actual = formatter.format(spanned, string1, string2)
47 |
48 | val span = (actual as? Spanned)?.getSpans(0, actual.length, StyleSpan::class.java)?.first()
49 |
50 | assertNotNull(span)
51 | }
52 |
53 | @Test
54 | fun `Given a string a span around a format placeholder When we format it Then the span is at the correct start location`() {
55 | val actual = formatter.format(spanned, string1, string2)
56 |
57 | val span = (actual as? Spanned)?.getSpans(0, actual.length, StyleSpan::class.java)?.first()
58 |
59 | assertEquals(5, (actual as? Spanned)?.getSpanStart(span) ?: 0)
60 | }
61 |
62 | @Test
63 | fun `Given a string with a span around a format placeholder When we format it Then the span is in the correct location`() {
64 | val actual = formatter.format(spanned, string1, string2)
65 |
66 | val span = (actual as? Spanned)?.getSpans(0, actual.length, StyleSpan::class.java)?.first()
67 |
68 | assertEquals(12, (actual as? Spanned)?.getSpanEnd(span) ?: 0)
69 | }
70 |
71 | @Test
72 | fun `Given a string with a span around plain text When we format it Then the span is still present`() {
73 | val actual = formatter.format(spanned, string1, string2)
74 |
75 | val span = (actual as? Spanned)?.getSpans(0, actual.length, UnderlineSpan::class.java)?.first()
76 |
77 | assertNotNull(span)
78 | }
79 |
80 | @Test
81 | fun `Given a string a span around plain text When we format it Then the span is at the correct start location`() {
82 | val actual = formatter.format(spanned, string1, string2)
83 |
84 | val span = (actual as? Spanned)?.getSpans(0, actual.length, UnderlineSpan::class.java)?.first()
85 |
86 | assertEquals(13, (actual as? Spanned)?.getSpanStart(span) ?: 0)
87 | }
88 |
89 | @Test
90 | fun `Given a string with a span around plain text When we format it Then the span is in the correct location`() {
91 | val actual = formatter.format(spanned, string1, string2)
92 |
93 | val span = (actual as? Spanned)?.getSpans(0, actual.length, UnderlineSpan::class.java)?.first()
94 |
95 | assertEquals(15, (actual as? Spanned)?.getSpanEnd(span) ?: 0)
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/library/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker:
--------------------------------------------------------------------------------
1 | mock-maker-inline
2 |
--------------------------------------------------------------------------------
/publish.gradle:
--------------------------------------------------------------------------------
1 | def pomConfig = {
2 | licenses {
3 | license {
4 | name 'The Apache Software License, Version 2.0'
5 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
6 | }
7 | }
8 | developers {
9 | developer {
10 | id 'stylingandroid'
11 | name 'Styling Android'
12 | email 'support@stylingandroid.com'
13 | }
14 | }
15 | scm {
16 | connection 'https://github.com/StylingAndroid/Rialto.git'
17 | developerConnection 'https://github.com/StylingAndroid/Rialto.git'
18 | url siteUrl
19 | }
20 | }
21 |
22 | def publicationNames = []
23 | publishing.publications {
24 | android.libraryVariants.all { variant ->
25 | if (variant.buildType.name == "debug") return // Prevents publishing debug library
26 |
27 | def flavored = !variant.flavorName.isEmpty()
28 |
29 | /**
30 | * Translates "_" in flavor names to "-" for artifactIds, because "-" in flavor name is an
31 | * illegal character, but is well used in artifactId names.
32 | */
33 | def variantArtifactId = flavored ? variant.flavorName.replace('_', '-') : project.name
34 |
35 | /**
36 | * If the javadoc destinationDir wasn't changed per flavor, the libraryVariants would
37 | * overwrite the javaDoc as all variants would write in the same directory
38 | * before the last javadoc jar would have been built, which would cause the last javadoc
39 | * jar to include classes from other flavors that it doesn't include.
40 | *
41 | * Yes, tricky.
42 | *
43 | * Note that "${buildDir}/docs/javadoc" is the default javadoc destinationDir.
44 | */
45 | def javaDocDestDir = file("${buildDir}/docs/javadoc ${flavored ? variantArtifactId : ""}")
46 |
47 | /**
48 | * Includes
49 | */
50 | def sourceDirs = variant.sourceSets.collect {
51 | it.javaDirectories // Also includes kotlin sources if any.
52 | }
53 | def javadoc = task("${variant.name}Javadoc", type: Javadoc) {
54 | description "Generates Javadoc for ${variant.name}."
55 | source = variant.javaCompile.source
56 | destinationDir = javaDocDestDir
57 | classpath += files(android.getBootClasspath().join(File.pathSeparator))
58 | classpath += files(configurations.compile)
59 | options.links("http://docs.oracle.com/javase/7/docs/api/")
60 | options.links("http://d.android.com/reference/")
61 | exclude '**/BuildConfig.java'
62 | exclude '**/R.java'
63 | failOnError false
64 | }
65 | def javadocJar = task("${variant.name}JavadocJar", type: Jar, dependsOn: javadoc) {
66 | description "Puts Javadoc for ${variant.name} in a jar."
67 | classifier = 'javadoc'
68 | from javadoc.destinationDir
69 | }
70 | def sourcesJar = task("${variant.name}SourcesJar", type: Jar) {
71 | description "Puts sources for ${variant.name} in a jar."
72 | from sourceDirs
73 | classifier = 'sources'
74 | }
75 |
76 | def publicationName = "rialto${variant.name.capitalize()}Library"
77 | publicationNames.add(publicationName)
78 |
79 | "$publicationName"(MavenPublication) {
80 | artifactId "rialto-" + variantArtifactId
81 | group groupId
82 | version libraryVersion
83 |
84 | artifact variant.outputs[0].packageLibrary // This is the aar library
85 | artifact sourcesJar
86 | artifact javadocJar
87 |
88 | pom {
89 | packaging 'aar'
90 | withXml {
91 | def root = asNode()
92 | root.appendNode("name", 'Rialto')
93 | root.appendNode("url", siteUrl)
94 | root.children().last() + pomConfig
95 | def depsNode = root["dependencies"][0] ?: root.appendNode("dependencies")
96 |
97 | def addDep = {
98 | if (it.group == null) return // Avoid empty dependency nodes
99 | def dependencyNode = depsNode.appendNode('dependency')
100 | dependencyNode.appendNode('groupId', it.group)
101 | dependencyNode.appendNode('artifactId', it.name)
102 | dependencyNode.appendNode('version', it.version)
103 | if (it.hasProperty('optional') && it.optional) {
104 | dependencyNode.appendNode('optional', 'true')
105 | }
106 | }
107 |
108 | // Add deps that everyone has
109 | configurations.compile.allDependencies.each addDep
110 | // Add flavor specific deps
111 | if (flavored) {
112 | configurations["${variant.flavorName}Compile"].allDependencies.each addDep
113 | }
114 | // NOTE: This library doesn't use builtTypes specific dependencies, so no need to add them.
115 | }
116 | }
117 | }
118 | }
119 | }
120 |
121 | group = groupId
122 | version = libraryVersion
123 |
124 | Properties properties = new Properties()
125 | File localProperties = project.rootProject.file('local.properties');
126 | if (localProperties.exists()) {
127 | properties.load(localProperties.newDataInputStream())
128 | } else {
129 | properties.put("bintray.user", System.getenv("BINTRAY_USER"))
130 | properties.put("bintray.apikey", System.getenv("BINTRAY_API_KEY"))
131 | }
132 |
133 | afterEvaluate {
134 | bintray {
135 | user = properties.getProperty("bintray.user")
136 | key = properties.getProperty("bintray.apikey")
137 | publications = publicationNames
138 | dryRun = false
139 |
140 | override = true
141 | pkg {
142 | repo = 'rialto'
143 | name = project.name
144 | //desc = libraryDesc
145 | websiteUrl = siteUrl
146 | issueTrackerUrl = 'https://github.com/StylingAndroid/Rialto/issues'
147 | vcsUrl = gitUrl
148 | licenses = ['Apache-2.0']
149 | labels = ['aar', 'android']
150 | publicDownloadNumbers = true
151 | githubRepo = 'StylingAndroid/Rialto'
152 | }
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':kotlinApp', ':library', ':javaApp'
2 |
--------------------------------------------------------------------------------