Mehedi Hassan Piash [Sr. Software Engineer]

November 26, 2023

Country search list with flag in jetpack compose

November 26, 2023 Posted by Piash , No comments

A country search list is a common use case for Android app development. we can develop a country search list with a flag using Android SDK and Jetpack compose. Now it's super easy to implement it using a lazy column. So let’s start step by step.

Step 1. We need a country list with the country flag. we can get it from Locale.

fun getCountries(): ArrayList<String> {
val isoCountryCodes: Array<String> = Locale.getISOCountries()
val countriesWithEmojis: ArrayList<String> = arrayListOf()
for (countryCode in isoCountryCodes) {
val locale = Locale("", countryCode)
val countryName: String = locale.displayCountry.
val flagOffset = 0x1F1E6
val asciiOffset = 0x41
val firstChar = Character.codePointAt(countryCode, 0) - asciiOffset + flagOffset
val secondChar = Character.codePointAt(countryCode, 1) - asciiOffset + flagOffset
val flag =
(String(Character.toChars(firstChar)) + String(Character.toChars(secondChar)))
countriesWithEmojis.add("$countryName $flag")
}
return countriesWithEmojis
}

Step 2. We have our country list with the country flag. Let’s implement it TextField with search functionality.

@Composable
fun CountryList() {
val searchText = rememberSaveable { mutableStateOf("") }
val countries = remember { mutableStateOf(getCountries()) }
var filteredCountries: ArrayList<String>

Column(
Modifier
.fillMaxWidth()
.padding(16.dp)
) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = searchText.value,
onValueChange = {
searchText.value = it
},
trailingIcon = {
Icon(
Icons.Default.Clear,
contentDescription = "clear text",
modifier = Modifier
.clickable {
searchText.value = ""
}
)
}
)
LazyColumn(Modifier.padding(top = 8.dp)) {
filteredCountries = if (searchText.value.isEmpty()) {
countries.value
} else {
val resultList = ArrayList<String>()
for (country in countries.value) {
if (country.lowercase(Locale.getDefault())
.contains(searchText.value.lowercase(Locale.getDefault()))
) {
resultList.add(country)
}
}
resultList
}
items(filteredCountries, itemContent = { item ->
Text(modifier = Modifier.padding(top = 6.dp), text = item)
Divider(modifier = Modifier.padding(top = 6.dp))
})
}
}
}

Ref: github link
Ref: medium


0 comments:

Post a Comment