Jetpack Compose - Row Clipping Children When Width Increases - android-jetpack-compose

Here on the right , I have a list of items in a composable , Every item is inside a row , All the items are inside a column
All the children of the are getting clipped to fit the screen which I don't want , I want these items to render completely even if outside of screen since I have a zoomable container above them
As you can see how text in the text field is all in one line vertically rather than expanding the width , This is the problem
Code :
Row(
modifier = modifier.zIndex(3f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
SimpleNodesList(
modifier = Modifier.padding(8.dp),
parentNode = state.center,
nodes = state.center.left,
renderRight = false,
)
SimpleNode(node = state.center, parentNode = null)
SimpleNodesList(
modifier = Modifier.padding(8.dp),
parentNode = state.center,
nodes = state.center.right,
renderLeft = false
)
}
Simple Nodes List is a column of rows , I have one column on left and one on the right , If the width of the left column increases , right row get's clipped by the screen

Using this modifier does the job for the row , In my case I also needed this layout modifier , wrapContentSize(unbounded = true) was working but children weren't clickable for some reason outside the bounds of the zoom container !
I also had to create a modifier zoomable rather than use a zoomable box , so the zoomable touch events would be dispatched on the this composable rather than the parent !
modifier = Modifier
.layout { measurable, constraints ->
val r =
measurable.measure(constraints = constraints.copy(maxWidth = Constraints.Infinity))
layout(r.measuredWidth, r.measuredHeight, placementBlock = {
r.placeWithLayer(0, 0, 0f) {
}
})
}
.wrapContentSize(unbounded = true)

If you are using hard-coded width for the text, applying Modifier.wrapContentSize() on every container might do the job

Use SimpleFlowRow in place of Row. It will fix the clipping issue.

Related

How to scroll to a certain item in a Column(Modifier.verticalScroll())?

I have a Column with TextViews with indices from -10 to 10.
Column(
modifier = modifier
.verticalScroll(
state = scrollState,
enabled = isScrollEnabled,
reverseScrolling = reverseScrollDirection
)) {
for(i in -10..10) {
TextView("Index $i")
}
}
Naturally, this Column start with -10 and is incrementing by 1 until 10; so I have to scroll forward all the 21 indices (picture left hand side).
How can I align 0 to the beginning, so that I start the view scrollable either 10 back until -10 or 10 forward until 10 (see attached picture right hand side)?
Column doesn't have a concept of item, it has just a bunch of composable functions called inside of it. Because of that, ScrollState only has a method to scroll to position in pixels.
If you know the height of your items, you can calculate the pixel position and pass it to rememberScrollState(). Otherwise, you can use LazyColumn which can scroll to specific item.

Avoid one frame delay in calculating child size

I have to create a reusable component that tries to achieve this goal: I have a column that can have content that's larger than the screen height. On the bottom of the screen we have panel with gradient background that can contain button or something else (it's basically a slot in the component). This bottom panel have to be always visible on the screen, and in case of the column being bigger than screen - bottom panel have to be on the top of this column. Gradient background does a nice UX effect so user knows what is going on. It looks like that:
I have that solved, but here's the challenge. The column content have to be scrollable to be on top of the bottom panel when scrolled to the end. Current solution I have is to add a spacer on the bottom of this column. This spacer have the calculated height of the bottom parent. And here's the issue - right now we have calculation done in onSizeChanged which basically results in additional frame needed for the spacer to have correct size.
We did not observe any negative impact of that performance or UX wise. The spacer height calculation never does anything that user can see, but I still want to solve that properly.
AFAIK this can be done using custom Layout, but that seems a little bit excessive for what I want to achieve. Is there another way to do this properly?
Current solution:
#Composable
fun FloatingPanelColumn(
modifier: Modifier = Modifier,
contentModifier: Modifier = Modifier,
contentHorizontalAlignment: Alignment.Horizontal = Alignment.Start,
bottomPanelContent: #Composable ColumnScope.() -> Unit,
content: #Composable ColumnScope.() -> Unit
) {
val scrollState = rememberScrollState()
var contentSize by remember {
mutableStateOf(1)
}
Box(modifier) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(state = scrollState)
.then(contentModifier),
horizontalAlignment = contentHorizontalAlignment,
) {
content()
val contentSizeInDp = with(LocalDensity.current) { contentSize.toDp() }
Spacer(modifier = Modifier.height(contentSizeInDp))
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.onSizeChanged {
contentSize = it.height
}
.wrapContentHeight()
.align(Alignment.BottomStart)
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color(0x00FAFCFF),
Color(0xFFF6F9FB),
)
)
),
content = bottomPanelContent
)
}
}
The best way to depend on an other view size during layout is using SubcomposeLayout:
SubcomposeLayout { constraints ->
// subcompose the view you need to measure first
val bottomPanel = subcompose("bottomPanel") {
Column(
// ...
)
}[0].measure(constraints)
// use calculated value in next views layout, like bottomPanel.height
val mainList = subcompose("mainList") {
LazyColumn(
contentPadding = PaddingValues(bottom = bottomPanel.height.toDp())
) {
// ...
}
}[0].measure(constraints)
layout(mainList.width, mainList.height) {
mainList.place(0, 0)
bottomPanel.place(
(mainList.width - bottomPanel.width) / 2,
mainList.height - bottomPanel.height
)
}
}

How to make ClickableText accessible to screen readers

This code creates a ClickableText element in Jetpack Compose Composable:
ClickableText(
text = forgotPasswordAnnotatedString,
onClick = {
context.startActivity(intent)
},
modifier = Modifier
.padding(top = mediumPadding)
)
The annotated string is defined here to make the text look like a link:
val forgotPasswordAnnotatedString = buildAnnotatedString {
append(stringResource(R.string.forgot_password))
addStyle(
style = SpanStyle(
textDecoration = TextDecoration.Underline,
color = Color.White,
fontSize = 16.sp,
fontWeight = FontWeight.Medium
),
start = 0,
end = 21,
)
}
When I encounter this text using the TalkBalk screen reader in Android, the screenreader does not make it clear that this is clickable text that will do something which tapped on. The reader just reads the text.
Is there a way to make it clear to the screen reader that this text is interactive? Otherwise should I just use a button and style it to look like a link?
It looks like your intention is for the whole text to be clickable? In which you best option is probably a TextButton as suggested by
Gabriele Mariotti.
But if you wan't only part of the link to be clickable, or to have multiple clickable sections, the best I've been able to land on is to draw an invisible box overtop of the Text. It means that I can control the touch target of the clickable area to be at least 48.dp and can use the semantics{} modifier to control how a screen reader interprets it.
Would welcome any suggestions.
// remember variables to hold the start and end position of the clickable text
val startX = remember { mutableStateOf(0f) }
val endX = remember { mutableStateOf(0f) }
// convert to Dp and work out width of button
val buttonPaddingX = with(LocalDensity.current) { startX.value.toDp() }
val buttonWidth = with(LocalDensity.current) { (endX.value - startX.value).toDp() }
Text(
text = forgotPasswordAnnotatedString,
onTextLayout = {
startX.value = it.getBoundingBox(0).left // where 0 is the start index of the range you want to be clickable
endX.value = it.getBoundingBox(21 - 1).right // where 21 is the end index of the range you want to be clickable
}
)
Note that buttonPaddingX is relative to the Text position not the Window, so you may have to surround both in a Box{} or use ConstraintLayout.
Then to draw the invisible box
Box(modifier = Modifier
.sizeIn(minWidth = 48.dp, minHeight = 48.dp) // minimum touch target size
.padding(start = buttonPaddingX)
.width(buttonWidth)
// .background(Color.Magenta.copy(alpha = 0.5f)) // uncomment this to debug where the box is drawn
.clickable(onClick = { context.startActivity(intent) })
.semantics {
// tell TalkBack whatever you need to here
role = Role.Button
contentDescription = "Insert button description here"
}
)
In my code I'm using pushStringAnnotation(TAG, annotation) rather than reference string indexes directly. That way I can get the start and end index of the clickable area with annotatedString.getStringAnnotations(TAG,0,annotatedString.length).first(). Useful if there a multiple links within the text.
It's disappointing that ClickableText doesn't have accessibility in mind from the get go, hopefully we'll be able to use it again in a future update.
Adding .semantics.contentDescription to the Modifier changes what is read by the screen reader. I had to word contentDescription to make it clear that this was a link to reset the your password.
The screen reader still doesn't recognize the element a clickable but hopefully the description will be useful to convey to the user that this element is interactive.
ClickableText(
text = forgotPasswordAnnotatedString,
onClick = {
context.startActivity(intent)
},
modifier = Modifier
.padding(top = mediumPadding)
// new code here:
.semantics {
contentDescription = "Forgot your password? link"
}
)

How to drag something behind another view

I'm trying to write a calendar like custom view as described in this blog post, which is also kind of like an Excel spreadsheet. Headers on the top and column counts on the left. Those are stickied to the top and left
https://danielrampelt.com/blog/jetpack-compose-custom-schedule-layout-part-1/
Unlike this blog post, which adds a horizontal / vertical scroll modifier on the content which keeps the headers in place works, I need to be able to drag my content in all directions.
It looked like I needed to use a pointInput with a detectDragGestures, but when I use that, it drags like i want, the headers are pinned to the top and move left/right and the column counts are pinned to the left and move up and down
But the schedule content scrolls over the columns/headers as i drag them upwards or left.
I need the dragged content to go behind the header/column indicators.
My layout is like this
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
Column(
modifier = modifier.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
offsetX = (offsetX + dragAmount.x).coerceIn((-1 * unitWidth.toPx() * unitList.count()), 0f)
offsetY = (offsetY + dragAmount.y).coerceIn(-1 * hourHeight.toPx() * 24, 0f)
}
}
) {
Header(modifier = Modifier.offset { IntOffset(offsetX.roundToInt(), 0) } )
Row(modifier = Modifier.weight(1f)) {
SideBar( modifier = Modifier.offset { IntOffset(0, offsetY.roundToInt())})
Schedule( modifier = Modifier.offset { IntOffset(offsetX.roundToInt() + unitWidth.roundToPx(), offsetY.roundToInt()) }.weight(1f)) } )
)
}
How do I enable dragging in any direction, and not overlap the other views? I want the content to be hidden / vanish behind the headers as it goes into them.
Just set the z-index of the headers and stuff to something like 5 and that of the draggable to a lower value. It will automatically be clipped upon appropriate position attainment

Awesome 3.5 - two panels (wiboxes) at the top

Before migrating to Awesome 3.5.1 I had two panels at the top of my screen (on top of each other, sort of) and none at the bottom. The code I used to achieve this pre-3.5.* is below:
-- Create the wibox
mywibox[s] = awful.wibox({ position = "top", height = "32", screen = s })
-- Add widgets to the wibox - order matters
mywibox[s].widgets = {
{
{
-- Upper left section
mylauncher,
mytaglist[s],
mypromptbox[s],
-- My custom widgets, separators etc...
layout = awful.widget.layout.horizontal.leftright
},
{
-- Upper right section
mylayoutbox[s],
mytextclock,
-- More widgets, separators, etc...
s == 1 and mysystray or nil,
layout = awful.widget.layout.horizontal.rightleft
},
},
{
-- Lower section (only the tasklist)
mytasklist[s],
},
layout = awful.widget.layout.vertical.flex,
height = mywibox[s].height
}
Now I'm having a hard time trying to figure out how to achieve the same with the 3.5 configuration. At the moment I use pretty basic one panel (with most of the widgets) on top, and one (with the tasklist) at the bottom. The code can be seen below:
-- Create the wibox
mywibox[s] = awful.wibox({ position = "top", height = "18", screen = s })
mywibox2[s] = awful.wibox({ position = "bottom", height = "18", screen = s })
-- Widgets that are aligned to the left
local left_layout = wibox.layout.fixed.horizontal()
left_layout:add(mylauncher)
left_layout:add(mytaglist[s])
left_layout:add(mypromptbox[s])
-- My custom widgets, separators, etc...
-- Widgets that are aligned to the right
local right_layout = wibox.layout.fixed.horizontal()
if s == 1 then right_layout:add(wibox.widget.systray()) end
-- My custom widgets, separators, etc...
right_layout:add(mytextclock)
right_layout:add(mylayoutbox[s])
-- Now bring it all together
local layout = wibox.layout.align.horizontal()
layout:set_left(left_layout)
layout:set_right(right_layout)
local layout2 = wibox.layout.align.horizontal()
layout2:set_middle(mytasklist[s])
mywibox[s]:set_widget(layout)
mywibox2[s]:set_widget(layout2)
If anyone has ideas how to edit my current rc.lua to make it work as the upper code did in Awesome 3.4.*, that'd be greatly appreciated.
You could try something like this, no idea if it does exactly what you want (32 is the height of your wibox according to your code):
local const = wibox.layout.constraint()
const:set_widget(layout)
const:set_strategy("exact")
const:set_height(32/2)
local l = wibox.layout.fixed.vertical()
l:add(const)
l:add(mytasklist[s])
mywibox[s]:set_widget(l)
First it creates a "constraint" layout which makes sure that the layout "layout" (the widgets that should be shown on the top) always get a size of 16px. Then it stacks this constraint layout ontop of the tasklist and displays the result in the wibox.
Some of this code could be shortened a bit in the latest version, but I am not sure if 3.5.1 has those convenience arguments already.
I've done similar with following code:
wiboxes["top"]=awful.wibox({position="top",height=26})
local top_layout = wibox.layout.fixed.horizontal()
sublayout["cpu"] = wibox.layout.fixed.horizontal()
for i=2,3 do
sublayout["cpu" .. i] = wibox.layout.fixed.horizontal()
sublayout["cpu" .. i]:add(graphs["cpu"]..i) -- the graphs table already initialized
sublayout["cpu" .. i]:add(textboxes["cpu"]..i) -- textboxes table already initialized
sublayout["cpu"]:add(sublayout["cpu"..i)
end
.....
top_layout:add(sublayout["cpu"])
.....
wiboxes["top"]:set_widget(top_layout)
With this code I've two graphs and textboxes to see the CPUs usage (every core), first is on top, second is down. It should work with taglist or any other widget.

Resources