How to change values of variable using Spinner? - android

How do I change the value of a variable using the spinner widget.
strings.xml
<string name="selected_item">Selected item:</string>
<string-array name="Languages">
<item>English</item>
<item>Latin</item>
<item>French</item>
</string-array>
mainactivity
val spinner = findViewById<Spinner>(R.id.spinner)
if (spinner != null) {
val adapter = ArrayAdapter(
this,
android.R.layout.simple_spinner_item, languages
)
spinner.adapter = adapter
spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View, position: Int, id: Long
) {
//what to do here?
}
}
}
suppose I want to change the value of this variable
strokeManager.lang = "en"

So you will want to use the position to access it from the list that you used to populate the spinner.
strokeManager.lang = languageMapToLangCode[languages.get(position)]
This should be defined in your class somewhere the spinner can access it
val languageMapToLangCode: HashMap<String, String> = hashMapOf("French" to "fr", "Latin" to "ln", "English to "en")

Related

Problem with Array<String> resource files

In my project I use resource files with arrays of strings in them, then I get a single String and check if it is in this array, which doesn't work
Here's some code:
//putting an array from resource file into variable
val categoryOne: Array<String> = resources.getStringArray(R.array.categoryOne_array)
val values: Array<String> = resources.getStringArray(R.array.categories_array)
//getting the string from spinner
var text = "blank"
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
text = values[p2]
Log.d("ASDASD", text)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
return
}
}
//checking if string is in the array
var currentGroup = "0"
if(categoryOne.contains(text)){
currentGroup = "1"
}
No matter what the value of "text" is, value of currentGroup stays 0
Here's the resource files also:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="categories_array">
<item>Бег. ОРУ</item>
<item>Кросс</item>
<item>Игры</item>
<item>Сил. упр.</item>
<item>Скор. эст.</item>
<item>Плавание</item>
<item>Борьба</item>
<item>Имит. упр</item>
<item>Упр. со скакалкой</item>
<item>Упр. с эспандером</item>
<item>Бой с тенью</item>
<item>Имит. упр. с утяж.</item>
<item>Упр. с медболом</item>
<item>Прыжковая работа</item>
<item>Стрейчинг</item>
<item>Отр. со слабым парт.</item>
<item>Отр. с сильным парт.</item>
<item>Слабый партнер</item>
<item>Сильный партнер</item>
<item>Мешки</item>
<item>Подушки</item>
<item>Груши</item>
<item>Лапы</item>
<item>Вольные бои</item>
<item>Спаринг</item>
<item>Соревн. бои</item>
</string-array>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="categoryOne_array">
<item>Бег. ОРУ</item>
<item>Кросс</item>
<item>Игры</item>
<item>Сил. упр.</item>
<item>Скор. эст.</item>
<item>Плавание</item>
<item>Борьба</item>
<item>Имит. упр</item>
<item>Упр. со скакалкой</item>
<item>Упр. с эспандером</item>
<item>Бой с тенью</item>
<item>Имит. упр. с утяж.</item>
<item>Упр. с медболом</item>
<item>Прыжковая работа</item>
<item>Стрейчинг</item>
</string-array>
</resources>
I hope I shared all code relevant to the question, if I didn't, please tell me and I shall provide it
Problem is "contains" is also case-sensitive. You have to use ignore case.
Something like
val array:Array<String> = resources.getStringArray(R.array.yourarray);
val test = "two"
for(item in array) {
if(item.equals(test, ignoreCase = true)) {
return true
}
}

Kotlin - Spinner Fragments Not Populating

I have looked at EVERY thread on here but cant seem to figure out why my Spinner isn't populating. I have tried all of these setups and cant seem to get my Spinners to populate. The app runs fine but nothing appears in the dropdowns.
In .kt file
//Setting Spinner Info
val weight_units = resources.getStringArray(R.array.weight_units)
val nut_spinner = binding.nutSpinner
val units = arrayOf("One", "Two", "Three")
if (nut_spinner != null) {
/*
val t = inflater.inflate(com.example.cc_tabbed.R.layout.fragment_main, container, false)
val spinner = t.findViewById<Spinner>(R.id.nutSpinner) as Spinner
val adapter = ArrayAdapter.createFromResource(
this,
R.array.weight_units, android.R.layout.simple_spinner_item
)/*
//val nut_adapter = ArrayAdapter<String>(requireContext(), android.R.layout.simple_spinner_item, weight_units.toList())
//val nut_adapter = ArrayAdapter<String>(requireActivity(), android.R.layout.simple_spinner_item, weight_units)
//val nut_adapter = activity?.let { ArrayAdapter<String>(it, android.R.layout.simple_spinner_item, weight_units) }
//val nut_adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, weight_units)
//nut_spinner.adapter = nut_adapter
strings.xml
<resources>
<string name="app_name">CC-Tabbed</string>
<string name="tab_text_1">Converter</string>
<string name="tab_text_2">Local Database</string>
<string-array name="weight_units">
<item>lb</item>
<item>oz</item>
<item>gram</item>
</string-array>
</resources>
The relevant Spinner in the .xml file
<Spinner
android:id="#+id/desSpinner"
android:layout_width="97dp"
android:layout_height="36dp"
android:layout_marginTop="76dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
Can anyone provide me any direction here? I am VERY new to programming in general and have sortof just stumbled my way to a working version of my Android App but Im learning as I go and have a hiccup here.
Thanks!
To populate data in Spinner component via xml you can use the attribute android:entries and define an array of strings into the strings.xml file like below:
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/spinnerData" />
where #array/spinnerData is define in your strings.xml like below:
<resources>
<string-array name="spinnerData">
<item>Spinner Item 1</item>
<item>Spinner Item 2</item>
<item>Spinner Item 3</item>
</string-array>
</resources>
or Programmatically in Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val spinner = view.findViewById<Spinner>(R.id.spinner)
val spinnerData = arrayOf("Spinner Item 1", "Spinner Item 2", "Spinner Item 3", "Spinner Item 4")
spinner.adapter = ArrayAdapter<String>(requireContext(), android.R.layout.simple_spinner_dropdown_item, spinnerData)
}
Result:

How can I discriminate the selected item of a Spinner by its text when using multilanguage items in Android?

I am trying to discriminate the selected item of a Spinner by its (multilanguage) text.
Here is my default strings.xml content:
<string-array name="spinner_items">
<item>length</item>
<item>weight</item>
<item>temperature</item>
</string-array>
And this is another strings.xml (Italian language) content:
<string-array name="spinner_items">
<item>lunghezza</item>
<item>peso</item>
<item>temperatura</item>
</string-array>
I set up my Spinner items in this way:
val items = resources.getStringArray(R.array.spinner_items)
spinner.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, items)
And then I add the item selected listener:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
when(spinner.getItemAtPosition(position).toString()) {
"length" -> actionLength()
"lunghezza" -> actionLength()
"weight" -> actionWeight()
"peso" -> actionWeight()
"temperature" -> actionTemperature()
"temperatura" -> actionTemperature()
}
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
Everything works fine but the problem is that everytime I add a new language locale, I have to remember to add the specific string translation inside the when block.
Is there a more "dynamic" way to do this?
I had the same problem in the past and here is how I solved it.
Edit your strings.xml files by adding a string resource name for each items in your array, for example:
Default strings.xml
<string name="length">length</string>
<string name="weight">weight</string>
<string name="temperature">temperature</string>
<string-array name="spinner_items">
<item>#string/length</item>
<item>#string/weight</item>
<item>#string/temperature</item>
</string-array>
Italian strings.xml
<string name="length">lunghezza</string>
<string name="weight">peso</string>
<string name="temperature">temperatura</string>
<string-array name="spinner_items">
<item>#string/length</item>
<item>#string/weight</item>
<item>#string/temperature</item>
</string-array>
So in your code, you'll have:
when(spinner.getItemAtPosition(position).toString()) {
getString(R.string.length) -> actionLength()
getString(R.string.weight) -> actionWeight()
getString(R.string.temperature) -> actionTemperature()
}
I hope I was helpful!
Just use the position:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
when(position) {
0 -> actionLength()
1 -> actionWeight()
2 -> actionTemperature()
}
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
In your array use:
<string-array name="spinner_items">
<item>#string/length</item>
<item>#string/weight</item>
<item>#string/temperature</item>
</string-array>

Android Kotlin Get Value of Selected Spinner Item

I'm using AndroidStudio 4.1.1 and kotlin
I'm having issues trying to get the value of a selected item in a spinner view/item. My first attempt, and many threads say to do it this way, is:
val spinner = findViewById<Spinner>(R.id.wMuscleGroup) as Spinner
val selectedText = spinner.getSelectedItem().toString()
This does not work for me. selectedText shows nothing in a Toast or a println
I also tried this, which I also found many threads for:
val spinner = findViewById<Spinner>(R.id.wMuscleGroup) as Spinner
if (spinner != null) {
val adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, muscleGroups )
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val selectedText = muscleGroups[position]
println("Muscle Group selected is $selectedText") // <-- this works
}
override fun onNothingSelected(parent: AdapterView<*>) {
// write code to perform some action
}
}
}
// selectedText is not seen here:
println("Muscle Group selected is $selectedText")
This works and I can see selectedString in my println, in the onItemSelected function inside the block. But, how do I get this value to be seen outside of this block of code? I need to use this value in a class object and a database write. I've tried declaring selectedString outside/above the if (spinner != null), but that does not seem to work either.
Thanks for any help.
Your Spinner does not have a value selected by default. Hence calling spinner.getSelectedItem() returns null and null.toString() returns an empty String.
Your code will work only if the user has selected an option from the Spinner first. You can set a initial value by using spinner.setSelection(position).
If you want to use the selected value outside the selection, you can use a global variable as follows:
val spinner = findViewById<Spinner>(R.id.wMuscleGroup) as Spinner
var selectedText = muscleGroups.first() // as default
if (spinner != null) {
val adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, muscleGroups )
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
selectedText = muscleGroups[position]
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
}
If you want to try something with selectedText, you should use it inside onItemSelected function.

How to fix Android Spinner selection if it is not working?

Android Spinner is not working, the API is working and the Spinner's list of items is working. However, the item selection is not working.
class PlayerSignup2Activity : AppCompatActivity() {
private lateinit var positions : List<Position>
val positionSpinner = positionsSpinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.example.app.R.layout.activity_user_signup2)
//Positions from API
positions = APIService.getPositions(this)
val spinnerAdapter = ArrayAdapter(this, R.layout.spinner_item, positions)
spinnerAdapter.setDropDownViewResource(R.layout.spinner_item)
positionSpinner.adapter = spinnerAdapter
}
Spinner list
After selecting any item
Any idea on how to fix this?!
Try with this
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
In Kotlin
class MainActivity : /** Other Classes, */AdapterView.OnItemSelectedListener {
var list_of_items = arrayOf("Item 1", "Item 2", "Item 3")
override fun onCreate(savedInstanceState: Bundle?) {
spinner!!.setOnItemSelectedListener(this)
// Create an ArrayAdapter using a simple spinner layout and languages array
val aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, list_of_items)
// Set layout to use when the list of choices appear
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Set Adapter to Spinner
spinner!!.setAdapter(aa)
}
override fun onItemSelected(arg0: AdapterView<*>, arg1: View, position: Int, id:Long{
// use position to know the selected item
//here you will get the answwer
}
override fun onNothingSelected(arg0: AdapterView<*>) {
}
}
try using prompt for adding title in .XML file
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"/>
or try adding 1 more item that contains whatever title you want like "select position" on index 0.
positions.add("select position");
positions.add("value 1");
after adding values to list set spinner value to index 0 by default using below code.
mSpinner.setSelection(0) .
and on Item Selected check if index 0 or value is "select position" then ignore selection else perform action you want.
private lateinit var positions : List<Position>
//add dummy data first
positions.add(Position("select position"));
//Positions from API
positions.addAll(APIService.getPositions(this));

Categories

Resources