Spinner的setOnItemSelectedListener不起作用

来源:互联网 发布:佛山网站seo推广 编辑:程序博客网 时间:2024/06/08 06:01
测试程序如下:
sp_allImg.setOnItemClickListener(new AdapterView.OnItemClickListener() {      @Override      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {      test.setText("你点击了Spinner的一个列表项!");      }});

其中,sp_allImg是一个Spinner对象

运行异常如下:

 java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.

查看源码:

 /**     * <p>A spinner does not support item click events. Calling this method     * will raise an exception.</p>     * <p>Instead use {@link AdapterView#setOnItemSelectedListener}.     *     * @param l this listener will be ignored     */

出错原因:Spinner组件不支持item点击事件,即Spinner的setOnItemClickListener无效,可以用setOnItemSelectedListener替代

更改后的测试代码:

sp_allImg.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {                @Override                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                    select_content1 = sp_allImg.getSelectedItem().toString();                    select_content2 = sp_allImg.getItemAtPosition(position).toString();                    test.setText("data[position]:"+data[position]+", select_content1:"+select_content1+", select_content2="+select_content2);                }                @Override                public void onNothingSelected(AdapterView<?> parent) {                }            });

其中,select_content1和select_content2是String类型, test是TextView对象

另外,若在xml中有设置Spinner的prompt属性,则注意prompt的属性值不能直接是文本字符串,而要使用引用。在strings.xml中设置如下:

    <string name="prompt_choose_album">请选择相册:</string>

在xml中设置如下:

  <Spinner
            android:id="@+id/sp_allImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:prompt="@string/prompt_choose_album"
            style="@android:style/Widget.Spinner"/>

   

总结:遇到问题,要习惯查看源码

0 0
原创粉丝点击