HTML in Jetpack Compose Text - android-jetpack-compose

I tried to enable HTML strings, especially with links e.g.:
"We are a team of professionals working hard to provide free learning content."
I used it like explained here by Akram Hussain:
val body = "We are a team of professionals working hard to provide free learning content."
val text = HtmlCompat.fromHtml(body, Html.FROM_HTML_MODE_LEGACY)
// HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_LEGACY)
Text(
text = text.toString(),
style = myStyle,
overflow = TextOverflow.Ellipsis,
maxLines = 4,
modifier = Modifier
.clickable(
enabled = true,
onClick = { },
indication = rememberRipple(bounded = true),
interactionSource = MutableInteractionSource(),
)
.animateContentSize(animationSpec = spring()),
onTextLayout = {
//
}
)
in a androidx.compose.material.TextKt.kt Text. Unfortunately, the text is shown, but no link is highlighted and link is not working at all.

Related

Bug in default behavior of ScalingLazyColumn (Jetpack Compose Wear OS)

I'm using ScalingLazyColumn with a very long Text inside as follows:
#Preview(device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true)
#Composable
fun Test(modifier: Modifier = Modifier) {
val scalingLazyState = remember { ScalingLazyListState() }
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = modifier,
positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }
) {
ScalingLazyColumn(
modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),
state = scalingLazyState,
) {
item {
Text(
longText,
Modifier
.padding(top = 20.dp, start = 16.dp, end = 16.dp, bottom = 48.dp),
textAlign = TextAlign.Center,
)
}
}
}
}
val longText =
"Take the plunge\n" +
"\n" +
"commit oneself to a course of action about which one is nervous.\n" +
"\n" +
"\"she wondered whether to enter for the race, but decided to take the plunge\"\n" +
"\"They're finally taking the plunge and getting married.\"\n" +
"\n" +
"\n" +
"plunge:\n" +
"jump or dive quickly and energetically.\n" +
"\"our daughters whooped as they plunged into the sea\"\n"
But for some reason when I launch the app the focus goes to the bottom of the text, instead of the beginning, which looks like a bug. I've tried playing with different parameters of ScalingLazyColumn (anchorType, autoCentering, scalingParams) to no avail.
Any idea how to fix it and make the ScalingLazyColumn focus on the beginning of the first element when I launch the app?
Switching off autoCentering is an option, but I would try and avoid it in most cases as it will will make handling getting the padding right on different devices sizes more difficult and often results in being able to over scroll the list items either at the beginning or the end.
I am not sure exactly what you want to achieve when you say that you want the focus to be on the start of the first item but the following should give you what you need.
Set the state initial item to 0
Set the anchor type to ScalingLazyListAnchorType.ItemStart
Remove top padding from your item
Apply an offset to the state initialItem initialCenterItemScrollOffset to shift the start of you item up a little.
Optionally adjust the autoCentering to make sure that the limit of the scrolling matches the initial position selected in the state
#Preview(device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true)
#Composable
fun SingleItemSLCWithLongText(modifier: Modifier = Modifier) {
val scalingLazyState = remember { ScalingLazyListState(initialCenterItemIndex = 0, initialCenterItemScrollOffset = 80) }
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = modifier.background(Color.Black),
positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }
) {
ScalingLazyColumn(
modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),
autoCentering = AutoCenteringParams(itemIndex = 0, itemOffset = 80),
state = scalingLazyState,
anchorType = ScalingLazyListAnchorType.ItemStart
) {
item {
Text(
longText,
Modifier
.padding(start = 16.dp, end = 16.dp, bottom = 48.dp),
textAlign = TextAlign.Center,
)
}
}
}
}
Here is a screenshot of how the screen initially looks
Initial screen
This test activity let's you play with all the params to see starting position
https://github.com/google/horologist/blob/a1241ff25b7008f7c1337f4425b98d14ce30d96d/sample/src/main/java/com/google/android/horologist/scratch/ScratchActivity.kt
After a few hours of frustration I finally found a solution.
If you read the documentation for ScalingLazyColumn it says:
"If the developer wants custom control over position and spacing they
can switch off autoCentering and provide contentPadding."
So all you need to do is to just add autoCentering = null in ScalingLazyColumn.
This is a working code where the focus will be in the beginning of the Text:
val scalingLazyState = remember { ScalingLazyListState() }
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = modifier,
positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }
) {
ScalingLazyColumn(
modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),
state = scalingLazyState,
autoCentering = null,
) {
item {
Text(
longText,
Modifier
.padding(top = 20.dp, start = 16.dp, end = 16.dp, bottom = 48.dp),
textAlign = TextAlign.Center,
)
}
}
}
ScalingLazyListState defaults to the center of the second item (index 1). You can tell it to instead start in the first item and even jn the ScalingLazyColumn parameters use the start of items.
val scalingLazyState = remember { ScalingLazyListState(initialCenterItemIndex = 0) }
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = Modifier,
positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }
) {
ScalingLazyColumn(
modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),
state = scalingLazyState,
anchorType = ScalingLazyListAnchorType.ItemStart
) {
item {
Text(
longText,
Modifier
.padding(top = 20.dp, start = 16.dp, end = 16.dp, bottom = 48.dp),
textAlign = TextAlign.Center,
)
}
}
}

Why is MediumTopAppBar (and Large) showing two TextField in compose?

I am trying to make the title of a screen editable.
MediumTopAppBar(
title = {
val name: String? = "Some Title"
var input by remember { mutableStateOf(name ?: "") }
when (state.isEditingTitle) {
true ->
TextField(
value = input,
onValueChange = { input = it },
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = {
callbacks.onEditTitleChange(editTitle = false, updatedTitle = input)
})
)
false -> {
Text(
modifier = Modifier.clickable { callbacks.onEditTitleChange(true, null) },
text = name ?: "(No Title)"
)
}
}
},
... more app bar parameters
}
When I click on the title Text(...) and the view gets recomposed the AppBar shows two TextFields
How do I ignore the top one and only show the one in the bottom, like the Text() is only shown in the bottom?
(Fyi: the two TextInputs have their own remembered state and calls the callback with their own respective value)
Bonus question: How do I handle the remembered state "input" so that it resets every time the onDone keyboard action is triggered? Instead of val name: String? = "Some Title" it would of course be something in the line of val name: String? = state.stateModel.title
I found out why it does this, but I have no idea how to solve it (except for just making my own views and placing it close by)
It's easy to see when looking at the function for the MediumTopBar
// androidx.compose.material3.AppBar.kt
#ExperimentalMaterial3Api
#Composable
fun MediumTopAppBar(
title: #Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: #Composable () -> Unit = {},
actions: #Composable RowScope.() -> Unit = {},
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
colors: TopAppBarColors = TopAppBarDefaults.mediumTopAppBarColors(),
scrollBehavior: TopAppBarScrollBehavior? = null
) {
TwoRowsTopAppBar(
modifier = modifier,
title = title,
titleTextStyle = MaterialTheme.typography.fromToken(TopAppBarMediumTokens.HeadlineFont),
smallTitleTextStyle = MaterialTheme.typography.fromToken(TopAppBarSmallTokens.HeadlineFont),
titleBottomPadding = MediumTitleBottomPadding,
smallTitle = title, // <- this thing, right here
navigationIcon = navigationIcon,
actions = actions,
colors = colors,
windowInsets = windowInsets,
maxHeight = TopAppBarMediumTokens.ContainerHeight,
pinnedHeight = TopAppBarSmallTokens.ContainerHeight,
scrollBehavior = scrollBehavior
)
}
There's some internal state shenanigans going on, probably checking for a Text being shown in the 2nd TopAppBarLayout (more digging required to find that), but not for any other view.
TwoRowsTopAppBar and TopAppBarLayout are not public, and can't be used directly.
This is explains why, but it would be interesting to see how to solve it (still using Medium or Large -TopAppBar)
it is stupid thing devs overlooked and should be warned against, at least. The answer is do not give default colors to your Typography TextStyles.
private val BodySmall = TextStyle(
fontSize = 10.sp,
lineHeight = 12.sp,
fontWeight = FontWeight.SemiBold,
fontFamily = Manrope,
color = Color.Black // REMOVE THIS
)
val OurTypography = Typography(
...
bodySmall = BodySmall
)

Jetpack Compose - Show trailingIcon in BasicTextField?

TextField has way too much padding by default for the screen I'm building, so I'm forced to use BasicTextField (see: this post on default TextField padding)
The problem is, BasicTextField doesn't take in a trailingIcon parameter. Is there a way to get around this?
Starting with 1.2.0 you can use the TextFieldDecorationBox with the BasicTextField. Here you can use the trailingIcon and contentPadding attributes:
BasicTextField(
value = value,
onValueChange = onValueChange,
interactionSource = interactionSource,
enabled = enabled,
singleLine = singleLine
) {
TextFieldDefaults.TextFieldDecorationBox(
value = value,
innerTextField = it,
singleLine = singleLine,
enabled = enabled,
visualTransformation = VisualTransformation.None,
trailingIcon = { /* ... */ },
interactionSource = interactionSource,
contentPadding = TextFieldDefaults.textFieldWithoutLabelPadding(
//...top = 0.dp, bottom = 0.dp
)
)
}

How to access nested widgets properties in Awesome

I'm trying to access the properties of the following widget:
local cpu_widget = wibox.widget{
{
max_value = 100,
paddings = 1,
border_width = 2,
widget = wibox.widget.progressbar,
},
{
font = beautiful.font_type .. "8",
widget = wibox.widget.textbox,
},
forced_height = 100,
forced_width = 20,
direction = 'east',
layout = wibox.container.rotate,
}
I've tried through the conventional way, using cpu_widget[1].value or cpu_widget[2].text, but that didn't work.
Any thoughts on how I could do that?
See the "Accessing Widgets" on https://awesomewm.org/doc/api/documentation/03-declarative-layout.md.html (I can't seem to link to this section directly)
Basically: You can add id = "bar" and id = "text" to your widgets and use these identifiers to retrieve the widgets again.
In case Elv13 ever sees this answer: You did great work on the docs!

How to vary the width of TextBox views using Rikulo Anchor Layout

I am new to Dart and Rikulo.
class NameView extends Section
{
View parentVu;
// the inputs
DropDownList titleDdl, suffixDdl;
TextBox firstNameTBox, middleNameTBox, lastNameTBox;
// the labels
TextView titleLbl, firstNameLbl, middleNameLbl, lastNameLbl, suffixLbl;
List<String> titles = [ 'Dr', 'Hon', 'Miss', 'Mr', 'Mrs', 'Prof', 'Sir' ];
List<String> suffixes = ['I', 'II', 'III', 'IV', 'Junior', 'Senior'];
NameView()
{
parentVu = new View()
..style.background = 'cyan'
..addToDocument();
titleLbl = new TextView( 'Title' );
parentVu.addChild( titleLbl );
titleDdl = new DropDownList( model : new DefaultListModel( titles ) )
..profile.anchorView = titleLbl
..profile.location = 'east center';
parentVu.addChild( titleDdl );
firstNameLbl = new TextView( 'First' )
..profile.anchorView = titleDdl
..profile.location = 'east center';
parentVu.addChild(firstNameLbl );
firstNameTBox = new TextBox( null, 'text' )
..profile.anchorView = firstNameLbl
..profile.location = 'east center';
//..profile.width = 'flex';
parentVu.addChild( firstNameTBox );
}
The program renders. However, it does not uses the entire width of the browser (FireFox).
I have tried for the TextBoxes
profile.width = 'flex'
but it does not work.
Any help is appreciated.
Firefox? Did you test it with Dartium? Notice that you have to compile it to JS before you can test it with browsers other than Dartium.
BTW, from your implementation, NameView seems not related to parentVu at all. If it is just a controller, it needs not to extend from Section (i.e., it doesn't have to be a view).
If a view is anchored to another, both location and size will depend on the view it anchors. In your case, if specifying flex to TextBox, its width will be the same as FirstNameLb1. It is why it is so small.
You can listen to the layout event such as:
firstNameTBox.on.layout.listen((_) {
firstNameTBox.width = parentVu.width;
});
Note: You need to do some calculation to get the right width.
See also Layout Overview

Resources