旋转器上的监听器

时间:2017-02-28 11:16:46

标签: android listener onclicklistener android-spinner

此代码从列表中向Spinner添加字符串 如何实现一个监听器,以便我可以从Spinner中获取单击或轻击的字符串?

spinner = (Spinner) findViewById(R.id.spinner);
List<String> list = new ArrayList<String>();

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(dataAdapter);

2 个答案:

答案 0 :(得分:7)

您可以使用此代码

 spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
    {
        String selectedItem = parent.getItemAtPosition(position).toString(); //this is your selected item
    }
    public void onNothingSelected(AdapterView<?> parent) 
    {

    }           
});

答案 1 :(得分:2)

任何想要Kotlin的人都可以这样:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
        override fun onNothingSelected(p0: AdapterView<*>?) {
        }

        override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long){
       }
    }