KeyboardOptions.Default.copy() vs KeyboardOptions(). When to use? - android-jetpack-compose

This is from a TextField composable
When to use "Default Copy"? Does it matter?
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Text
)
// vs //
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Text
)

if you want to keep same instance and want to update one of the properties and preserve other ones you can use .copy().
Consider this example with a data class Person
data class Person(
val name: String = "",
val age: Int = 1
)
and some use-case like this
val johnPerson = Person("John", 21)
val unknownPerson = Person(age = 23)
I can simply copy unknownPerson and keep the age 23 and finally set the person's name like this
val knownPerson = unknownPerson.copy(name = "Mr. Kebab")
prints
Person(name=Mr. Kebab, age=23)

It does not matter. They both end up doing the same thing. KeyboardOptions class is not a data class, and even if it were, the copy() method would still create a new instance.

Related

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
)

Dynamically building subtables in a table

I'm trying to figure out how to dynamically build a series of sub-tables inside a lua table. For example
function BuildsubTable()
local oTable = {}
local name = {"P1","P2"}
for i = 1, 2 do
oTable[i] = {name = name[i], "x" = i + 2, "y" = i + 1}
end
return oTable
end
expected output:
oTable = {
{name = "P1", "x"=3, "y"=2},
{name = "P2", "x"=4, "y"=3}
}
Which obviously doesn't work, but you get the idea of what I'm trying to do. This is a rather simple task but in LUA 5.3 this is proving to be difficult. I cannot find a good example of building a table in this manner. Any solutions or other ideas would be appreciated. In Python I would use a class or a simple dictionary.
Your problem is that you quote the string indices. The generic syntax for declaring a table key inside the table constructor is [<key>] = <value>, for example, [20] = 20 or ["x"] = i + 2.
A shorthand for ["<key>"] = <value>, that is, for string indices that are valid variable names, you can write <key> = <value>, for example x = i + 2.
In your code you use a mix of both and write { ..., "x" = i + 2, ... }. A quick google search shows me that in Python, which you mention, you quote string keys in dictionaries, so you probably mixed that up with Lua?
EDIT: I noticed this a bit late, but you can also use ipairs to iterate the first table and table.insert to insert values:
function BuildsubTable()
local oTable = {}
local name = {"P1","P2"}
for i,name in ipairs(name) do
table.insert(oTable, {name = name, "x" = i + 2, "y" = i + 1})
end
return oTable
end
Use
oTable[i] = {name = name[i], x = i + 2, y = i + 1}
DarkWiiPlayers & lhf's answers are the proper way.
But here is how you can fix your current code if you intend to use a string as a key
function BuildsubTable()
local oTable = {}
local name = {"P1","P2"}
for i = 1, 2 do
oTable[i] = {name = name[i], ["x"] = i + 2, ["y"] = i + 1}
end
return oTable
end
Output
{
[1] = { ['name'] = 'P1', ['x'] = 3, ['y'] = 2},
[2] = { ['name'] = 'P2', ['x'] = 4, ['y'] = 3}
}

Emulate string to label dict

Since Bazel does not provide a way to map labels to strings, I am wondering how to work around this via Skylark.
Following my partial horrible "workaround".
First the statics:
_INDEX_COUNT = 50
def _build_label_mapping():
lmap = {}
for i in range(_INDEX_COUNT):
lmap ["map_name%s" % i] = attr.string()
lmap ["map_label%s" % i] = attr.label(allow_files = True)
return lmap
_LABEL_MAPPING = _build_label_mapping()
And in the implementation:
item_pairs = {}
for i in range(_INDEX_COUNT):
id = getattr(ctx.attr, "map_name%s" % i)
if not id:
continue
mapl = getattr(ctx.attr, "map_label%s" % i)
if len(mapl.files):
item_pairs[id] = list(mapl.files)[0].path
else:
item_pairs[id] = ""
if item_pairs:
arguments += [
"--map", str(item_pairs), # Pass json data
]
And then the rule:
_foo = rule(
implementation = _impl,
attrs = dict({
"srcs": attr.label_list(allow_files = True, mandatory = True),
}.items() + _LABEL_MAPPING.items()),
Which needs to be wrapped like:
def foo(map={}, **kwargs):
map_args = {}
# TODO: Check whether order of items is defined
for i, item in enumerate(textures.items()):
key, value = item
map_args["map_name%s" % i] = key
map_args["map_label%s" % i] = value
return _foo(
**dict(map_args.items() + kwargs.items())
)
Is there a better way of doing that in Skylark?
To rephrase your question, you want to create a rule attribute mapping from string to label?
This is currently not supported (see list of attributes), but you can file a feature request for this.
Do you think using "label_keyed_string_dict" is a reasonable workaround? (it won't work if you have duplicated keys)

Simple way to convert a "string" into a [[string]]?

Is there a way to convert or create a new [[bracket style string]] based on an existing 'quote style string'?
s = "one\ntwo" -- how the string was created
s2 = [[one\ntwo]] -- what i want the new string to be
Escaping the escape sequence seems to achieve the desired effect, at least in this case.
s2 = string.gsub(s, "\n", "\\n")
> print(s2)
one\ntwo
One way is to make a table that has all the possible escape sequences:
local t = {["\a"] = [[\a]],
["\b"] = [[\b]],
["\f"] = [[\f]],
["\n"] = [[\n]],
["\r"] = [[\r]],
["\t"] = [[\t]],
["\r"] = [[\r]],
["\\"] = [[\\]],
["\""] = [["]],
["\'"] = [[']],
}
local s2 = s:gsub(".", t)

Copy Object Properties to a Map by Value not by Reference

I'm not sure where i'm going wrong, but it seems that I'm not able to copy properties from an object instance and assign them to a map without the values being changed after saving the instance.
This is a sample class:
class Product {
String productName
String proudctDescription
int quantityOnHand
}
Once the form is submitted and it's sent to my controller, I can access the values and manipulate them from the productInstance.properties map that is available from the instance. I want to copy the properties to another map to preserve the values before committing them during an edit. So let's say we are editing a record and these are the values stored in the db: productName = "My Product", productDescription = "My Product Description" and quantityOnHand = 100.
I want to copy them to:
def propertiesBefore = productInstance.properties
This did not work, because when I save the productInstance, the values in propertiesBefore change to whatever the instance had.
So I tried this:
productInstance.properties.each { k,v -> propertiesBefore[k] = v }
Same thing happened again. I am not sure how to copy by value, it seems no matter what I try it copies by reference instead.
EDIT
As per the request of Pawel P., this is the code that I tested:
class Product {
String productName
String productDescription
int quantityOnHand
}
def productInstance = new Product(productName: "Some name", productDescription: "Desciption", quantityOnHand: 10)
def propertiesBefore = [:]
productInstance.properties.each { k,v -> propertiesBefore[k] = (v instanceof Cloneable) ? v.clone() : v }
productInstance.productName = "x"
productInstance.productDescription = "y"
productInstance.quantityOnHand = 9
println propertiesBefore.quantityOnHand // this will print the same as the one after the save()
productInstance.save(flush:true)
println propertiesBefore.quantityOnHand // this will print the same as the one above the save()
Without cloning, copying hash-map [:]'s values to a new hash-map [:]'s space can also be done by "pushing" the first one over, which would achieve the same result that you desired (copy by value)!
def APE = [:]
APE= [tail: 1, body: "hairy", hungry: "VERY!!!"]
def CAVEMAN = [:]
CAVEMAN << APE //push APE to CAVEMAN's space
//modify APE's values for CAVEMAN
CAVEMAN.tail = 0
CAVEMAN.body = "need clothes"
println "'APE': ${APE}"
println "'CAVEMAN': ${CAVEMAN}"
Output ==>
'APE': [tail:1, body:hairy, hungry:VERY!!!]
'CAVEMAN': [tail:0, body:need clothes, hungry:VERY!!!]
The problem is that you actually copy references to variables. To obtain copy of variable you should use clone(). Take a look:
class Product {
String productName
String productDescription
int quantityOnHand
}
def productInstance = new Product(productName: "Some name", productDescription: "Desciption", quantityOnHand: 10)
def propertiesBefore = [:]
productInstance.properties.each { k,v -> propertiesBefore[k] = (v instanceof Cloneable) ? v.clone() : v }
productInstance.productName = "x"
productInstance.productDescription = "y"
productInstance.quantityOnHand = 9
println productInstance.properties
println propertiesBefore
It prints:
[quantityOnHand:9, class:class Product, productName:x, productDescription:y]
[quantityOnHand:10, class:class Product, productName:Some name, productDescription:Desciption]
A simpler example for groovy using Hash-Map [:] can be like this:
def APE = [:]
APE= [tail: 1, body: "hairy", hungry: "VERY!!!"]
def CloneMe = APE //*APE as clone*
def CAVEMAN = [:] //*copy APE's values over thru mapping the clone*
CloneMe.each { key,value -> CAVEMAN[key] = (value instanceof Cloneable) ? value.clone() : value }
println "'CloneMe': ${CloneMe}"
//change some of the clone's values for CAVEMAN
CAVEMAN.tail = 0
CAVEMAN.body = "need clothes"
println "'APE': ${APE}"
println "'CAVEMAN': ${CAVEMAN}"
Output ==>
'CloneMe': [tail:1, body:hairy, hungry:VERY!!!]
'APE': [tail:1, body:hairy, hungry:VERY!!!]
'CAVEMAN': [tail:0, body:need clothes, hungry:VERY!!!]

Resources