Home > Blockchain >  How can I create a spinner by merging two string-arrays?
How can I create a spinner by merging two string-arrays?

Time:08-21

I am developing an Android application using Kotlin. I want to make a spinner that outputs two string-array at once, how can I merge String-array elements from the xml document? I tried using like a normal array, but it was not merged and only a runtime error occurred.

TestActivity.kt

class TestActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {

    private val vBinding by lazy {ActivityTestBinding.inflate(layoutInflater)}


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)
        setSpinner()
    }


    private fun setSpinner(){
        vBinding.testTopic1.adapter = ArrayAdapter.createFromResource(
            this,
            R.array.subject,
            android.R.layout.simple_spinner_item
        )
        vBinding.testTopic1.onItemSelectedListener = this
    }

    override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        if(p0!=null){
            when(p2){
                0 -> vBinding.testTopic2.adapter = ArrayAdapter.createFromResource(this, R.array.arrayA   R.array.arrayB android.R.layout.simple_spinner_item)    // didn't work here
                1 -> vBinding.testTopic2.adapter = ArrayAdapter.createFromResource(this, R.array.arrayA, android.R.layout.simple_spinner_item)
                2 -> vBinding.testTopic2.adapter = ArrayAdapter.createFromResource(this, R.array.arrayB, android.R.layout.simple_spinner_item)
            }
        }
    }

    override fun onNothingSelected(p0: AdapterView<*>?) {
    }

array.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string-array name="subject">
        <item>a</item>
        <item>b</item>
    </string-array>

    <string-array name="arrayA">
        <item>a1</item>
        <item>a2</item>
    </string-array>

    <string-array name="arrayB">
        <item>b1</item>
        <item>b2</item>
    </string-array>

</resources>

CodePudding user response:

You cannot merge arrays with ids like you have done. You need to get Array<String> and create adapter like below , instead of ArrayAdapter.createFromResource

1.  var adapter = ArrayAdapter(this,android.R.layout.simple_spinner_item,getMergedStringArray( R.array.arrayA,R.array.arrayB))

fun getMergedStringArray(@ArrayRes vararg arr :Int): Array<String> {
    return arr.flatMap {
        this.resources.getStringArray(it).asIterable()
    }.toTypedArray()
}

2.  var adapter =     ArrayAdapter(this,android.R.layout.simple_spinner_item,this.resources.getStringArray(R.array.arrayA)  this.resources.getStringArray(R.array.arrayB))
  • Related