Kotlin学习笔记——Spinner

2019-04-03  本文已影响0人  Jingtianer

android提供的spinner

class MainActivity : AppCompatActivity() {
    val strs = arrayOf("1", "2","3","4","5", "6", "7","8","9","10","11","12","13","14","15","16")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sp = findViewById<View>(R.id.spinner) as Spinner
        val startAdapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, strs)
        startAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
        sp.prompt = "请选择"
        sp.adapter = startAdapter
        sp.setSelection(0)
        var listen = myItemClickListener()
        sp.onItemSelectedListener = listen
    }
    internal inner class myItemClickListener : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            toast("你的选择是:${strs[position]}")
        }
    }
}

步骤

  1. 一个ArrayAdapter,参数分别是thisR.layout.support_simple_spinner_dropdown_itemArray<String>(到时候的item)
  2. 刚才的ArrayAdapter设置效率视窗资源,调用setDropDownViewResource函数,参数是R.layout.support_simple_spinner_dropdown_item
  3. ArrayAdapter赋值给spinneradapter成员
  4. 设置默认选项,setSelection
  5. 如果想让spinner为对话框形式的,在xml文件中设置android:spinnerMode="Dialog",spinnerprompt成员为设置对话框标题的接口
  6. 新建一个内部类,监听下拉选择,继承AdapterView.OnItemSelectedListener,重载onNothingSelectedonItemSelected两个方法
  7. 新建监听器对象,通过spinneronItemSelectedListener设置为监听器

anko库提供的spinner——selector

    val strs = Arrayof("1", "2", "3")
    aTextView.text = "假装这是一个spinner,其实我是TextView"
    aTextView.setOnClickListener {
        selector("请选择", strs) { i -> 
            toast("你的选择是:${strs[i]}")
        }
    }
上一篇下一篇

猜你喜欢

热点阅读