Android Spinner , set different value onItemselected - android

I want to set different values to a spinner when an item is selected, I set a list of country namse concatenate by country codes, on item selected event.
I want to set only the country code on view, but there is no method to set that value.
countryCodeSpinner.onItemSelectedListener = object : AdapterView.OnItemClickListener,
AdapterView.OnItemSelectedListener {
override fun onItemClick(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
countryCode = codesList[position]
}
}

You can do as following:
spinnerRangeForMap.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
if (position != 0) {
//Your code
}
}
}
and for item selected in spinner you can get as below:
spinnerRangeForMap.selectedItem.toString()

I added this code to get the view of the spinner and edit it after selecting :
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
if (position > 0) {
val code = codesList[position]
view!!.findViewById<TextView>(android.R.id.text1).text =
"+" + code.split("+")[1]
countryCode = code
}}

Related

Kotlin problem with Spinner inside Fragment

I have a problem with the spinner inside a fragment. The spinner is filled with data, but when I select an item I don't see logs, and in the spinner, it does not select elements. When I used nearly the same code as an activity it worked (Just changed the context to this in the adapter)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_edit_stoper, container, false)
val tagSpinner = view.findViewById<Spinner>(R.id.editSpinner)
val items: MutableList<String> = ArrayList("a","b","c")
tagSpinner.adapter = ArrayAdapter(this.requireActivity(), android.R.layout.simple_spinner_item, items) as SpinnerAdapter
tagSpinner.onItemSelectedListener = this
return view
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Log.d(TAG,"OnItemSelected: $type")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d(TAG,"error")
}
}
Is your fragment really a listener for spinner?
Write a custom listener and use that instead of your fragment.
inner class SpinnerStateChangeListener : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
// do sth here
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// do sth here
}
}
Now you can set your listener like this:
tagSpinner.onItemSelectedListener = SpinnerStateChangeListener()
Try moving your implementation from Fragment directly to spinner. remove override from class and instead of
tagSpinner.onItemSelectedListener = this
do
tagSpinner.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d(TAG,"error")
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Log.d(TAG,"OnItemSelected: $type")
}
}
The solution is to add requireActivity().applicationContext in the adapter to change the activityFragment to a context:
...
val items: MutableList<String> = ArrayList("a","b","c")
tagSpinner.adapter = ArrayAdapter(requireActivity().applicationContext, android.R.layout.simple_spinner_item, items) as SpinnerAdapter
tagSpinner.onItemSelectedListener = this
...

How to expand an onItemSelectedListener from a Custom View?

The custom view listen to the spinner and change the background and the header of the box, if the user choose an value, which is not the first:
//Listener, if the user choose a item in the spinner
sp_First.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
//Is not empty
if(sp_First.selectedItemId.toInt() != 0) {
ll_elementFirst.background = resources.getDrawable(R.drawable.border_green_padding, null)
txt_titleFirst.setTextColor(Color.parseColor("#007F0E"))
} else {
ll_elementFirst.background = resources.getDrawable(R.drawable.border_padding, null)
txt_titleFirst.setTextColor(Color.parseColor("#949494"))
}
}
}
This works perfect. But, I want in the Activity add another onItemSelectedListener, which do something if the choosen value is the third in the list. If I do this, I must overwrite the "onItemSelected"-Method and losing the background/text color-change.
Is there a good solution to expand the onItemSelected-Method?
Thanks and have a nice day!
So, I tried something and think, this is the solution:
I outsoured the actions in a seperate method in the class of the CustomView, call it at "onItemSelected" and in the class of my view, I created a new "AdapterView.OnItemSelectedListener"-object within I call the seperated method and my new instructions.
DualSpinner.kt
//Listener, if the user choose a item in the spinner
sp_First.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
seperatedMethod()
}
}
fun seperatedMethod() {
//Is not empty
if(sp_Second.selectedItemId.toInt() != 0) {
ll_elementSecond.background = resources.getDrawable(R.drawable.border_green_padding, null)
txt_pleasechooseSecond.visibility = View.GONE
txt_titleSecond.setTextColor(Color.parseColor("#007F0E"))
} else {
ll_elementSecond.background = resources.getDrawable(R.drawable.border_padding, null)
txt_pleasechooseSecond.visibility = View.VISIBLE
txt_titleSecond.setTextColor(Color.parseColor("#949494"))
}
//Is the other element also not empty?
if(sp_First.selectedItemId.toInt() != 0 && sp_Second.selectedItemId.toInt() != 0) {
ll_main.background = resources.getDrawable(R.drawable.border_green_padding, null)
txt_title.setTextColor(Color.parseColor("#007F0E"))
} else {
ll_main.background = resources.getDrawable(R.drawable.border_padding, null)
txt_title.setTextColor(Color.parseColor("#949494"))
}
}
Activity.kt
sp_MARKFLR.sp_Second.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
sp_MARKFLR.seperatedMethod()
if(sp_MARKFLR.sp_First.selectedItem.toString().contains("ohne Markierung")) {
sp_MARKFLRZ.setSelection(1, 1)
}
}
}

Kotlin Spinner selection

I created a custom spinner adapter, populated with data, on runtime it drops the list, but nothing can be selected. The selection works with the stock ArrayAdapter, but the custom. Please help, what am I missig...
DetailsActivity.kt:
'''class DetailsActivity : AppCompatActivity() {
.
.
.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.word_details)
val spinner: Spinner = findViewById(R.id.topic_spinner)
spinner.adapter = cAdapter(applicationContext, fillSpinner())
val listener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(parent: AdapterView<*>?, view: View, pos: Int, id: Long) {
Toast.makeText(applicationContext, "Selected: $pos", Toast.LENGTH_SHORT).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
spinner.onItemSelectedListener = listener
.
.
.
'''
fillSpinner function:
'''
fun fillSpinner(): ArrayList{
val topics = ArrayList<String>()
topics.clear()
val h_cursor = dbHandler.get_h_AllRow()
h_cursor.moveToFirst()
while (!h_cursor.isAfterLast){
topics.add(h_cursor.getString(h_cursor.getColumnIndex(DBHelper.H_COLUMN_TOPIC)))
h_cursor.moveToNext()
}
return topics
}
'''
cAdapter class:
'''
class cAdapter(val ctx: Context, val items: ArrayList) :
ArrayAdapter(ctx, 0, items) {
override fun getView(position: Int, recycledView: View?, parent: ViewGroup): View {
return this.createView(position, recycledView, parent)
}
override fun getDropDownView(position: Int, recycledView: View?, parent: ViewGroup): View {
return this.createView(position, recycledView, parent)
}
private fun createView(position: Int, recycledView: View?, parent: ViewGroup): View {
val item = getItem(position)
val view = recycledView ?: LayoutInflater.from(context).inflate(
R.layout.spinner_layout,
parent,
false)
view.IB_cancel.setImageResource(android.R.drawable.ic_delete)
view.IB_cancel.setOnClickListener {
Toast.makeText(context, "DELETE SOMETHING!", Toast.LENGTH_SHORT).show()
}
view.t_sp_holder.text = item
return view
}
}
'''
As I see, the problem should lie somewhere here in theese lines. Please give some advice, I am new at Kotlin.

Kotlin Android TextView KotlinNullPointerException

I decided to write small program in Kotlin. And now I have one problem which I can't fix. This is due to NullPointerException. And the Logcat always shows me an error in line where I wrote this textView_msg!!.text = "${currencyList[p2]}". Please help me.
This is my code
open class CurrencyActivity : AppCompatActivity() {
open var textView_msg: TextView? = null
open var textView: TextView? = null
open val currencyList = arrayOf("AUD","CAD","CHF","EUR","GBP","JPY","NZD","KHR","USD","CNY","THB","INR")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.currency_activty)
setUpSpinnerData()
}
//This method will be invoked to setup data of the spinner views
//to show lists of currency types for selection
fun setUpSpinnerData() {
textView_msg = findViewById(R.id.setCurrencyFrom) as TextView
textView = findViewById(R.id.setCurrencyTo) as TextView
val spFrom: Spinner = findViewById(R.id.fromCurrency)
spFrom.onItemSelectedListener = ItemSelectedFrom()
val afrom: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spFrom.adapter = afrom
val spTo: Spinner = findViewById(R.id.toCurrency)
spTo.onItemSelectedListener = ItemSelectedTo()
val ato: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spTo.adapter = ato
}
class ItemSelectedFrom: CurrencyActivity(), AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
//textView_msg = findViewById(R.id.setCurrencyFrom) as TextView
textView_msg!!.text = "${currencyList[p2]}"
}
}
class ItemSelectedTo : CurrencyActivity(), AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
//textView = findViewById(R.id.setCurrencyTo) as TextView
textView!!.text = "${currencyList[p2]}"
}
}
}`
Yes, I did it. Thanks everybody who tried to help me. I just a little bit rewrite it(but in comments I have an old code). This is my solution.
class CurrencyActivity : AppCompatActivity() {
var textView_msg: TextView ?= null
var textView: TextView ?= null
var currencyList = arrayOf("AUD","CAD","CHF","EUR","GBP","JPY","NZD","KHR","USD","CNY","THB","INR")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.currency_activty)
setUpSpinnerData()
}
//This method will be invoked to setup data of the spinner views
//to show lists of currency types for selection
fun setUpSpinnerData() {
val spFrom: Spinner = findViewById(R.id.fromCurrency)
spFrom.onItemSelectedListener = onItemSelectedListener0
val afrom: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spFrom.adapter = afrom
val spTo: Spinner = findViewById(R.id.toCurrency)
spTo.onItemSelectedListener = onItemSelectedListener1
val ato: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spTo.adapter = ato
}
var onItemSelectedListener0: OnItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
textView_msg = findViewById(R.id.LALALALA)
Log.e("KUKU", currencyList[position])
textView_msg?.text = "${currencyList[position]}"
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
var onItemSelectedListener1: OnItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
textView = findViewById(R.id.NANANANA)
textView?.text = "${currencyList[position]}"
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
// class ItemSelectedFrom: CurrencyActivity(), AdapterView.OnItemSelectedListener {
// override fun onNothingSelected(p0: AdapterView<*>?) {}
//
// override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
// textView_msg = findViewById(R.id.LALALALA)
// Log.e("KUKU", currencyList[position])
// textView_msg?.text = "${currencyList[position]}"
// }
// }
//
// class ItemSelectedTo : CurrencyActivity(), AdapterView.OnItemSelectedListener {
// override fun onNothingSelected(p0: AdapterView<*>?) {}
//
// override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
// textView = findViewById(R.id.NANANANA)
// textView?.text = "${currencyList[position]}"
// }
// }
}
And now what was the problem. Explaining.
var textView_msg: TextView ?= null
// Initialize it somewhere.
textView_msg?.text = "${currencyList[position]}" // Calls setText if textView_msg != null
textView_msg!!.text = "${currencyList[position]}" // Throws an exception if textView_msg == null

Android Kotlin onItemSelectedListener for spinner not working

I have a spinner with some items (strings).
I want to add the selected items to a list. I read online that I should use the onItemSelectedListenerrather than the onItemClickListener.
I implemented this but I don't know how to complete the step of adding it to the list.
class NewKitListActivity : AppCompatActivity() {
var spinnerArray = arrayOf("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
//var spinnerArray = arrayOf(DataService.kitList)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_kit_list)
val spinner = newKitItemSpinner
val spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray)
//selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = spinnerArrayAdapter
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val selectedItem = parent.getItemAtPosition(position).toString()
if (selectedItem == "Add new category") {
// do your stuff
}
} // to close the onItemSelected
override fun onNothingSelected(parent: AdapterView<*>) {
}
}}}
Thanks
(in Kotlin)Use this code:
yourSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Thanks this is helpful for me, Its working fine !
daysSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Add extension function
fun Spinner.selected(action: (position:Int) -> Unit) {
this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
action(position)
}
}
}
simple use
spinner.selected {
println(it) //selected position
}
string will not be able to check using '==' instead you need to use equals("string")
if (selectedItem.equals("Add new category")) {
// do your stuff
}
I implemented like this.
1. Create Empty Mutable List
2. Set onItemSelectedListner on spinner
3. When user select item add that to mutable list
Check my this answer for more info. It will help you: Android Koltin pass spinner values to mutable list
instead of:
var spinnerArray = arrayOf("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
try
var spinnerArray = mutableListOf<String>("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
just had the same situation when I was trying to get a sqlite tableĀ“s $_ID and populate the spinner with them
// Extends AdapterView.OnItemSelectedListener
class Dialogs : DialogFragment(), AdapterView.OnItemSelectedListener {}
//Somewhre in onCreate (I'm using databinding but you don't have to)
binding.spinnerDialogEstados.onItemSelectedListener = this
// then implement members...
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
TODO("Not yet implemented")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}

Categories

Resources