我正在处理Kotlin代码,需要使用在函数内部创建的值。我分享我的代码:
val Myspinner: Spinner = findViewById(R.id.spinner)
if (Myspinner!= null) {
val adapter = ArrayAdapter(this,
android.R.layout.simple_spinner_item, pulsatil)
Myspinner.adapter = adapter
}
Myspinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
//val pulsatil2 = Myspinner.selectedItem.toString()
override fun onNothingSelected(parent: AdapterView<*>?) {TODO("not implemented")}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val Spinnervalue: String = parent?.getItemAtPosition(position).toString()
}
}
val MyArrayList: MutableList<Spinnervalue> = ArrayList()
然后我想添加";Spinnervalue";至";MyArrayList";。我试图创建";Myfinalvalue";就像类的全局值,但它不起作用。
有什么想法吗?
提前感谢!
第一个问题是,您需要能够访问类中的任何位置的数组,所以"MyArrayList";必须是全球性的。第二,这里:
val MyArrayList: MutableList<Spinnervalue> = ArrayList()
你已经通过了";Spinnervalue";作为arraylist的类型,而添加到arraylist的值的类型实际上是String。所以活动中的最终代码应该是这样的:
class MainActivity : AppCompatActivity() {
val myArrayList = arrayListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Myspinner: Spinner = findViewById(R.id.spinner)
if (Myspinner!= null) {
val adapter = ArrayAdapter(this,
android.R.layout.simple_spinner_item, pulsatil)
Myspinner.adapter = adapter
}
Myspinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
//val pulsatil2 = Myspinner.selectedItem.toString()
override fun onNothingSelected(parent: AdapterView<*>?) {TODO("not implemented")}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val Spinnervalue: String = parent?.getItemAtPosition(position).toString()
myArrayList.add(Spinnervalue)
}
}
}
将arraylist放在顶部,然后像我发布的代码一样在onItemSelected函数中添加值。