my current code obtains items from a string array but how can the array be used to perform specific actions for specific strings? E.g. If I click the item containing the string "Anpan", I want a specific event to happen.
strings.xml
<resources>
<string name="app_name">Breads</string>
<!--Array (198 items)-->
<string-array name="array_breads">
<item>Aish merahrah</item>
...
<item>Zwieback</item>
</string-array>
</resources>
MainActivity.kt
class MainActivity : ComponentActivity() {
private var itemArray: Array<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
itemArray = resources.getStringArray(R.array.array_breads)
super.onCreate(savedInstanceState)
setContent {
AdaptiveTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MyScaffold(itemArray = itemArray as Array<out String>)
}
}
}
}
}
@Composable
fun MyScaffold(itemArray: Array<out String>) {
val context = LocalContext.current
Scaffold(
topBar = {
SmallTopAppBar(
title = {
Text(text = stringResource(id = R.string.breads))
}
)
},
content = {
val listState = rememberLazyListState()
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = listState,
contentPadding = PaddingValues(top = 64.dp, bottom = 80.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(itemArray) { item ->
Text(modifier = Modifier.padding(16.dp), text = item,
style = MaterialTheme.typography.titleLarge)
}
}
}
}
CodePudding user response:
Add clickable modifier on your Text component:
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = listState,
contentPadding = PaddingValues(top = 64.dp, bottom = 80.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(itemArray) { item ->
Text(modifier = Modifier
.padding(16.dp)
.clickable{// You can obtain 'item' here which item clicked.},
text = item,
style = MaterialTheme.typography.titleLarge)
}
}
CodePudding user response:
This seems to basic to be a post but here we go.
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = listState,
contentPadding = PaddingValues(top = 64.dp, bottom = 80.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(itemArray) { item ->
Text(
modifier = Modifier
.padding(16.dp)
.clickable {
if(item == 'Anpan') performSpecificTask()
else performGeneralTask()
},
text = item,
style = MaterialTheme.typography.titleLarge)
}
}
Here doSpecificTask()
and doGeneral...
is in reference to the task that you wish to do over there. Just replace the calls with your own code blocks.