【问题标题】:Android: Spinner item on click does't work if it is already selectedAndroid:如果已选中,则单击时微调器项目不起作用
【发布时间】:2012-06-26 08:49:34
【问题描述】:

我有一个带有 onItemSelected 交互的 Spinner,但 Api 规范怎么说:

This callback is invoked only when the newly selected position is different from the 
previously selected position or if there was no selected item.

我需要删除此限制,并且我希望在用户选择相同元素时也调用回调。如何做到这一点?
有人做过同样的事情吗?

对此的任何想法都会很明显..

【问题讨论】:

标签: android android-spinner


【解决方案1】:

i want that the callback is invoked also if the user select the same element. How to do that?

为 Spinner 设置 OnItemClickListener 将引发异常,使用 ItemSelectedListener 如果用户单击选定/相同的元素,您将不会收到通知。

我想克服这个限制的唯一方法是对 Spinner 项使用 CustomAdapter 并为适配器中的每个视图实现 setOnClickListener

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,并环顾四周。可能有多种方法可以让此功能发挥作用,但扩展微调器对我有用。你可以做一些类似于我发现here 的事情。

    因此,不要使用默认的 Android 微调器扩展它并向其添加一些将触发您的回调方法的代码。

    我想补充一点,在 Spinner 上使用 setOnItemClickListener 会引发文档中所述的异常:

    A spinner does not support item click events. Calling this method will raise an exception.
    

    【讨论】:

      【解决方案3】:

      在这种情况下,您必须制作一个自定义微调器:试试这个

      public class MySpinner extends Spinner{
      
      OnItemSelectedListener listener;
      
      public MySpinner(Context context, AttributeSet attrs)
      {
          super(context, attrs);
      }
      
      @Override
      public void setSelection(int position)
      {
          super.setSelection(position);
      
          if (position == getSelectedItemPosition())
          {
              listener.onItemSelected(null, null, position, 0);
          }       
      }
      
      public void setOnItemSelectedListener(OnItemSelectedListener listener)
      {
          this.listener = listener;
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多