为什么在使用自定义侦听器时会一直无限循环?

时间:2014-03-01 21:03:09

标签: java android interface adapter

我正在开发一个Android应用程序,我正在实现我自己的监听器,所以我的片段可以在选择一个微调器值时作出反应。问题是,当我在片段中调用refresh方法时,我会不断获得无限循环。

SpinnerAdapter:

 public interface OnSpinnerItemSelectedListener {
        public void onSpinnerItemSelected(int index);
 }
 public SpinnerAdapter(Activity context, OnSpinnerItemSelectedListener listener){
    super(context)
    mListener = listener;
 }
 private OnSpinnerItemSelectedListener mListener;
 Spinner spinner;//Already initialized and contains values, but I didn't think it would be important to show that here.
 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (mListener != null) {
                mListener.onSpinnerItemSelected(i);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });

片段适配器初始化:

SpinnerAdapter adapter =  new SpinnerAdapter(getActivity(), new  SpinnerAdapter.OnSpinnerItemSelectedListener() {
            @Override
            public void onSpinnerItemSelected(int index) {
                refreash(SpinnerFragment.this,getActivity());
            }
        });//calls the refresh method infinite number of times.   

刷新方法

    //the problem isn't the implementation, its just that interface keeps calling it repeatedly. 
 public void refreash(Fragment f,Context activity) {
        getFragmentManager().beginTransaction().replace(R.id.content_frame,f).commit();
    }

1 个答案:

答案 0 :(得分:0)

我认为错误可能出在您Fragment的{​​{1}}方法中。由于你有感觉,当你在onCreateView()上实际调用commit()时,它是一个无限循环,这可能是因为你已经在已经创建的FragmentManager上调用了onCreateView() ,所以你试图重新定义布局。

您的Fragment方法应如下所示:

onCreateView()