如果选择了非零位置,则旋转后旋转器的onItemSelected回调调用两次 [英] Spinner's onItemSelected callback called twice after a rotation if non-zero position is selected

查看:83
本文介绍了如果选择了非零位置,则旋转后旋转器的onItemSelected回调调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建活动时,我设置了一个微调器,为它分配了一个侦听器和一个初始值.我知道在应用程序初始化期间会自动调用onItemSelected回调.我感到奇怪的是,当设备旋转时,会两次发生这种情况,这给我带来了一些我不得不以某种方式必须解决的问题.如果微调框的初始选择为零,则不会发生.我能够找出问题所在,这是触发问题的最简单的活动:

When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the onItemSelected callback is called automatically during application initialization. What I find strange is that this happens twice when the device is rotated, causing me some problems that I will have to circumvent someway. This does not happen if the spinner initial selection is zero. I was able to isolate the issue, here's the simplest activity triggering it:

public class MainActivity extends Activity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i("Test","Activity onCreate");
    setContentView(R.layout.activity_main);
    ((Spinner)findViewById(R.id.spinner1)).setSelection(2);
    ((Spinner)findViewById(R.id.spinner1)).setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> spin, View selview, int pos, long selId)
{
    Log.i("Test","spin:"+spin+" sel:"+selview+" pos:"+pos+" selId:"+selId);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
}

这是启动应用程序然后旋转设备时显示的日志:

And here's the logcat shown when the application is started and then the device rotated:

    I/Test( 9881): spin:android.widget.Spinner@4052f508 sel:android.widget.TextView@40530b08 pos:2 selId:2
    I/Test( 9881): Activity onCreate
    I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2
    I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2

这是预期的行为吗?我想念什么吗?

Is this the expected behaviour? Am I missing something?

推荐答案

设法在另一个stackoverflow问题中找到解决方案:

Managed to find a solution in another stackoverflow question:

spinner.post(new Runnable() {
    public void run() {
        spinner.setOnItemSelectedListener(listener);
    }
});

这篇关于如果选择了非零位置,则旋转后旋转器的onItemSelected回调调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆