Spinner already Selected Item Selection 事件

Spinner already Selected Item Selection event

场景: 我正在使用 Spinner 进行日期范围选择,效果很好。问题是,有一个选项“自定义范围”,我必须在该选项上打开一个自定义日期范围选择器。虽然第一次运行正常。

问题是: 当用户再次单击它时,它不会调用 onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)(这是 Spinner 的一项功能)。但从用户的角度来看,这是一个错误。

有什么办法,我们可以在已选择的 Spinner 项目上获得任何选择事件?

你用过吗

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // your code here with selected **item position**
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }

});

要在 Spinner 中已选择的项目上调用事件,您可以这样做:

  1. 通过扩展 AppCompatSpinner:
  2. 创建您自己的 Spinner class
import android.content.Context
import android.util.AttributeSet
import android.util.Log

class MySpinner(context: Context, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatSpinner(
    context,
    attrs
)
{
    var listener: OnItemSelectedListener? = null

    override fun setSelection(position: Int)
    {
        super.setSelection(position)
        if (position == selectedItemPosition)
        {
            listener!!.onItemSelected(this, selectedView, position, selectedItemId)
        }
    }

    override fun setOnItemSelectedListener(listener: OnItemSelectedListener?)
    {
        this.listener = listener
    }
}
  1. 在您的布局中使用它:
<com.yourcompany.kotlintest.MySpinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
  1. 创建布局时执行此操作:
class MainActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val spinner = findViewById<MySpinner>(R.id.spinner)

        spinner.adapter = ArrayAdapter(
            this,
            android.R.layout.simple_spinner_dropdown_item,
            arrayListOf("One", "Two", "Three")
        )

        spinner.onItemSelectedListener = object :
                AdapterView.OnItemSelectedListener
        {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View, position: Int, id: Long
            )
            {
                Log.d("MyTag", "Click item at pos $position")
            }

            override fun onNothingSelected(parent: AdapterView<*>)
            {
                Log.d("MyTag", "Nothing selected")
            }
        }
    }
}

现在当您重新选择相同的项目功能将被执行