-
Notifications
You must be signed in to change notification settings - Fork 144
/
TextSnippets.kt
778 lines (714 loc) · 24 KB
/
TextSnippets.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "UNUSED_VARIABLE", "PreviewMustBeTopLevelFunction")
package com.example.compose.snippets.text
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.DisableSelection
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Cyan
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.PlatformTextStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.Hyphens
import androidx.compose.ui.text.style.LineBreak
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
/**
* This file lets DevRel track changes to snippets present in
* https://developer.android.com/jetpack/compose/text
*
* No action required if it's modified.
*/
private object SimpleTextSnippet {
// [START android_compose_text_simple_text]
@Composable
fun SimpleText() {
Text("Hello World")
}
// [END android_compose_text_simple_text]
}
private object StringResourceSnippet {
// [START android_compose_text_resource]
@Composable
fun StringResourceText() {
Text(stringResource(R.string.hello_world))
}
// [END android_compose_text_resource]
}
private object TextColorSnippet {
// [START android_compose_text_color]
@Composable
fun BlueText() {
Text("Hello World", color = Color.Blue)
}
// [END android_compose_text_color]
}
private object TextSizeSnippet {
// [START android_compose_text_size]
@Composable
fun BigText() {
Text("Hello World", fontSize = 30.sp)
}
// [END android_compose_text_size]
}
private object TextItalicSnippet {
// [START android_compose_text_italic]
@Composable
fun ItalicText() {
Text("Hello World", fontStyle = FontStyle.Italic)
}
// [END android_compose_text_italic]
}
private object TextBoldSnippet {
// [START android_compose_text_bold]
@Composable
fun BoldText() {
Text("Hello World", fontWeight = FontWeight.Bold)
}
// [END android_compose_text_bold]
}
private object TextAlignmentSnippet {
// [START android_compose_text_alignment]
@Composable
fun CenterText() {
Text(
"Hello World", textAlign = TextAlign.Center, modifier = Modifier.width(150.dp)
)
}
// [END android_compose_text_alignment]
}
private object TextShadowSnippet {
// [START android_compose_text_shadow]
@Composable
fun TextShadow() {
val offset = Offset(5.0f, 10.0f)
Text(
text = "Hello world!",
style = TextStyle(
fontSize = 24.sp,
shadow = Shadow(
color = Color.Blue, offset = offset, blurRadius = 3f
)
)
)
}
// [END android_compose_text_shadow]
}
private object TextMultipleFontsSnippet {
// [START android_compose_text_multiple_fonts]
@Composable
fun DifferentFonts() {
Column {
Text("Hello World", fontFamily = FontFamily.Serif)
Text("Hello World", fontFamily = FontFamily.SansSerif)
}
}
// [END android_compose_text_multiple_fonts]
}
@Composable
private fun TextDefineFontFamilySnippet() {
// [START android_compose_text_multiple_fonts_styles]
val firaSansFamily = FontFamily(
Font(R.font.firasans_light, FontWeight.Light),
Font(R.font.firasans_regular, FontWeight.Normal),
Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
Font(R.font.firasans_medium, FontWeight.Medium),
Font(R.font.firasans_bold, FontWeight.Bold)
)
// [END android_compose_text_multiple_fonts_styles]
}
@Composable
private fun TextFontWeightSnippet() {
// [START android_compose_text_font_weight]
Column {
Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Light)
Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Normal)
Text(
text = "text",
fontFamily = firaSansFamily,
fontWeight = FontWeight.Normal,
fontStyle = FontStyle.Italic
)
Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Medium)
Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Bold)
}
// [END android_compose_text_font_weight]
}
private object TextMultipleStylesSnippet {
// [START android_compose_text_multistyle]
@Composable
fun MultipleStylesInText() {
Text(
buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Blue)) {
append("H")
}
append("ello ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
append("W")
}
append("orld")
}
)
}
// [END android_compose_text_multistyle]
}
private object TextParagraphStyleSnippet {
// [START android_compose_text_paragraph_style]
@Composable
fun ParagraphStyle() {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
withStyle(style = SpanStyle(color = Color.Blue)) {
append("Hello\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold, color = Color.Red
)
) {
append("World\n")
}
append("Compose")
}
}
)
}
// [END android_compose_text_paragraph_style]
}
private object TextMaxLinesSnippet {
// [START android_compose_text_maxlines]
@Composable
fun LongText() {
Text("hello ".repeat(50), maxLines = 2)
}
// [END android_compose_text_maxlines]
}
private object TextOverflowSnippet {
// [START android_compose_text_overflow]
@Composable
fun OverflowedText() {
Text("Hello Compose ".repeat(50), maxLines = 2, overflow = TextOverflow.Ellipsis)
}
// [END android_compose_text_overflow]
}
private object TextBrushSnippet1 {
@Composable
fun TextStyledBrushSnippet(text: String) {
// [START android_compose_text_brush]
val gradientColors = listOf(Cyan, LightBlue, Purple /*...*/)
Text(
text = text,
style = TextStyle(
brush = Brush.linearGradient(
colors = gradientColors
)
)
)
// [END android_compose_text_brush]
}
}
private object TextBrushSnippet2 {
@Composable
fun TextStyledBrushSnippet() {
val rainbowColors: List<Color> = listOf()
// [START android_compose_text_textfield_brush]
var text by remember { mutableStateOf("") }
val brush = remember {
Brush.linearGradient(
colors = rainbowColors
)
}
TextField(
value = text, onValueChange = { text = it }, textStyle = TextStyle(brush = brush)
)
// [END android_compose_text_textfield_brush]
}
}
private object TextBrushSnippet3 {
@Composable
fun TextStyledBrushSnippet() {
val rainbowColors: List<Color> = listOf()
// [START android_compose_text_annotatedString_brush]
Text(
text = buildAnnotatedString {
append("Do not allow people to dim your shine\n")
withStyle(
SpanStyle(
brush = Brush.linearGradient(
colors = rainbowColors
)
)
) {
append("because they are blinded.")
}
append("\nTell them to put some sunglasses on.")
}
)
// [END android_compose_text_annotatedString_brush]
}
}
private object TextBrushSnippet4 {
@Composable
fun TextStyledBrushSnippet() {
val rainbowColors: List<Color> = listOf()
// [START android_compose_text_alpha_brush]
val brush = Brush.linearGradient(colors = rainbowColors)
buildAnnotatedString {
withStyle(
SpanStyle(
brush = brush, alpha = .5f
)
) {
append("Text in ")
}
withStyle(
SpanStyle(
brush = brush, alpha = 1f
)
) {
append("Compose ❤️")
}
}
// [END android_compose_text_alpha_brush]
}
}
private object TextIncludeFontPaddingSnippet {
@Composable
fun AlignedText(text: String) {
// [START android_compose_text_includeFontPadding]
Text(
text = text,
style = LocalTextStyle.current.merge(
TextStyle(
lineHeight = 2.5.em,
platformStyle = PlatformTextStyle(
includeFontPadding = false
),
lineHeightStyle = LineHeightStyle(
alignment = LineHeightStyle.Alignment.Center,
trim = LineHeightStyle.Trim.None
)
)
)
)
// [END android_compose_text_includeFontPadding]
}
}
private object TextSelectableSnippet {
// [START android_compose_text_selection]
@Composable
fun SelectableText() {
SelectionContainer {
Text("This text is selectable")
}
}
// [END android_compose_text_selection]
}
private object TextPartiallySelectableSnippet {
// [START android_compose_text_partial_selection]
@Composable
fun PartiallySelectableText() {
SelectionContainer {
Column {
Text("This text is selectable")
Text("This one too")
Text("This one as well")
DisableSelection {
Text("But not this one")
Text("Neither this one")
}
Text("But again, you can select this one")
Text("And this one too")
}
}
}
// [END android_compose_text_partial_selection]
}
private object TextClickableSnippet {
// [START android_compose_text_clickable]
@Composable
fun SimpleClickableText() {
ClickableText(text = AnnotatedString("Click Me"), onClick = { offset ->
Log.d("ClickableText", "$offset -th character is clicked.")
})
}
// [END android_compose_text_clickable]
}
private object TextClickableAnnotatedSnippet {
// [START android_compose_text_clickable_annotated]
@Composable
fun AnnotatedClickableText() {
val annotatedText = buildAnnotatedString {
append("Click ")
// We attach this *URL* annotation to the following content
// until `pop()` is called
pushStringAnnotation(
tag = "URL", annotation = "https://developer.android.com"
)
withStyle(
style = SpanStyle(
color = Color.Blue, fontWeight = FontWeight.Bold
)
) {
append("here")
}
pop()
}
ClickableText(text = annotatedText, onClick = { offset ->
// We check if there is an *URL* annotation attached to the text
// at the clicked position
annotatedText.getStringAnnotations(
tag = "URL", start = offset, end = offset
).firstOrNull()?.let { annotation ->
// If yes, we log its value
Log.d("Clicked URL", annotation.item)
}
})
}
// [END android_compose_text_clickable_annotated]
}
private object TextTextFieldSnippet {
// [START android_compose_text_textfield_filled]
@Composable
fun SimpleFilledTextFieldSample() {
var text by remember { mutableStateOf("Hello") }
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
// [END android_compose_text_textfield_filled]
}
private object TextOutlinedTextFieldSnippet {
// [START android_compose_text_textfield_outlined]
@Composable
fun SimpleOutlinedTextFieldSample() {
var text by remember { mutableStateOf("") }
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
// [END android_compose_text_textfield_outlined]
}
private object TextStylingTextFieldSnippet {
// [START android_compose_text_textfield_styled]
@Composable
fun StyledTextField() {
var value by remember { mutableStateOf("Hello\nWorld\nInvisible") }
TextField(
value = value,
onValueChange = { value = it },
label = { Text("Enter text") },
maxLines = 2,
textStyle = TextStyle(color = Color.Blue, fontWeight = FontWeight.Bold),
modifier = Modifier.padding(20.dp)
)
}
// [END android_compose_text_textfield_styled]
}
private object TextFormattingTextFieldSnippet {
// [START android_compose_text_textfield_visualtransformation]
@Composable
fun PasswordTextField() {
var password by rememberSaveable { mutableStateOf("") }
TextField(
value = password,
onValueChange = { password = it },
label = { Text("Enter password") },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
)
}
// [END android_compose_text_textfield_visualtransformation]
}
private object TextCleanInputSnippet {
// [START android_compose_text_textfield_clean_input]
@Composable
fun NoLeadingZeroes() {
var input by rememberSaveable { mutableStateOf("") }
TextField(
value = input,
onValueChange = { newText ->
input = newText.trimStart { it == '0' }
}
)
}
// [END android_compose_text_textfield_clean_input]
}
/** Effective State management **/
private object TextEffectiveStateManagement1 {
// [START android_compose_text_state_viewmodel]
class SignUpViewModel : ViewModel() {
var username by mutableStateOf("")
private set
/* ... */
}
// [END android_compose_text_state_viewmodel]
}
private object TextEffectiveStateManagement2 {
class UserRepository
val viewModel = SignUpViewModel(UserRepository())
// [START android_compose_text_state_management]
// SignUpViewModel.kt
class SignUpViewModel(private val userRepository: UserRepository) : ViewModel() {
var username by mutableStateOf("")
private set
fun updateUsername(input: String) {
username = input
}
}
// SignUpScreen.kt
@Composable
fun SignUpScreen(/*...*/) {
OutlinedTextField(
value = viewModel.username,
onValueChange = { username -> viewModel.updateUsername(username) }
/*...*/
)
}
// [END android_compose_text_state_management]
}
@Composable
private fun TextSample(samples: Map<String, @Composable ()->Unit>) {
MaterialTheme {
Box(
Modifier
.background(MaterialTheme.colorScheme.background)
.fillMaxWidth()
) {
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.padding(10.dp)
) {
samples.forEach { (title, content) ->
Row(Modifier.fillMaxWidth()) {
content()
Text(
text = title,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.titleLarge,
modifier = Modifier
.fillMaxWidth()
.align(Alignment.CenterVertically)
)
}
}
}
}
}
}
private const val SAMPLE_LONG_TEXT =
"Jetpack Compose is Android’s modern toolkit for building native UI. " +
"It simplifies and accelerates UI development on Android bringing your apps " +
"to life with less code, powerful tools, and intuitive Kotlin APIs. " +
"It makes building Android UI faster and easier."
@Composable
@Preview
fun LineBreakSample() {
// [START android_compose_text_line_break]
TextSample(
samples = mapOf(
"Simple" to {
Text(
text = SAMPLE_LONG_TEXT,
modifier = Modifier
.width(130.dp)
.border(BorderStroke(1.dp, Color.Gray)),
fontSize = 14.sp,
style = TextStyle.Default.copy(
lineBreak = LineBreak.Simple
)
)
},
"Paragraph" to {
Text(
text = SAMPLE_LONG_TEXT,
modifier = Modifier
.width(130.dp)
.border(BorderStroke(1.dp, Color.Gray)),
fontSize = 14.sp,
style = TextStyle.Default.copy(
lineBreak = LineBreak.Paragraph
)
)
}
)
)
// [END android_compose_text_line_break]
}
@Preview
@Composable
fun SmallScreenTextSnippet() {
// [START android_compose_text_paragraph]
TextSample(
samples = mapOf(
"Balanced" to {
val smallScreenAdaptedParagraph =
LineBreak.Paragraph.copy(strategy = LineBreak.Strategy.Balanced)
Text(
text = SAMPLE_LONG_TEXT,
modifier = Modifier
.width(200.dp)
.border(BorderStroke(1.dp, Color.Gray)),
fontSize = 14.sp,
style = TextStyle.Default.copy(
lineBreak = smallScreenAdaptedParagraph
)
)
},
"Default" to {
Text(
text = SAMPLE_LONG_TEXT,
modifier = Modifier
.width(200.dp)
.border(BorderStroke(1.dp, Color.Gray)),
fontSize = 14.sp,
style = TextStyle.Default
)
}
)
)
// [END android_compose_text_paragraph]
}
private object CJKTextSnippet {
@Composable
fun CJKSample() {
// [START android_compose_text_cjk]
val customTitleLineBreak = LineBreak(
strategy = LineBreak.Strategy.HighQuality,
strictness = LineBreak.Strictness.Strict,
wordBreak = LineBreak.WordBreak.Phrase
)
Text(
text = "あなたに寄り添う最先端のテクノロジー。",
modifier = Modifier.width(250.dp),
fontSize = 14.sp,
style = TextStyle.Default.copy(
lineBreak = customTitleLineBreak
)
)
// [END android_compose_text_cjk]
}
}
@Preview
@Composable
fun HyphenateTextSnippet() {
// [START android_compose_text_hyphen]
TextSample(
samples = mapOf(
"Hyphens - None" to {
Text(
text = SAMPLE_LONG_TEXT,
modifier = Modifier
.width(130.dp)
.border(BorderStroke(1.dp, Color.Gray)),
fontSize = 14.sp,
style = TextStyle.Default.copy(
lineBreak = LineBreak.Paragraph,
hyphens = Hyphens.None
)
)
},
"Hyphens - Auto" to {
Text(
text = SAMPLE_LONG_TEXT,
modifier = Modifier
.width(130.dp)
.border(BorderStroke(1.dp, Color.Gray)),
fontSize = 14.sp,
style = TextStyle.Default.copy(
lineBreak = LineBreak.Paragraph,
hyphens = Hyphens.Auto
)
)
}
)
)
// [END android_compose_text_hyphen]
}
@Preview(showBackground = true)
// [START android_compose_text_marquee]
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BasicMarqueeSample() {
// Marquee only animates when the content doesn't fit in the max width.
Column(Modifier.width(400.dp)) {
Text(
"Learn about why it's great to use Jetpack Compose",
modifier = Modifier.basicMarquee(),
fontSize = 50.sp
)
}
}
// [END android_compose_text_marquee]
// Using null just sets the font family to default, which is easier than supplying
// the actual font file in the snippets repo. This fixes a build warning.
private val firaSansFamily = null
val LightBlue = Color(0xFF0066FF)
val Purple = Color(0xFF800080)