自定义侦听器始终为null

时间:2013-06-02 03:35:31

标签: android

这是我的主要活动:

public class MainActivity extends BaseGameActivity implements  GameFragment.Listener {

    GameFragment mGameFragment;

    @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGameFragment = new GameFragment();
        mGameFragment.setListener(this);

    }

    @Override
    public void onGameEnded(int score) {
       ...
    }

}

这只是一个托管我游戏的片段。

public class GameFragment extends Fragment implements View.OnClickListener {

    public interface Listener {
        public void onGameEnded(int score);
    }

    Listener mListener = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.game_layout, container, false);

        checkSequence();

        return view;
    }

    public void setListener(Listener l) {
         mListener = l;
    }


    private void checkSequence() {
            if (mListener != null)
                 mListener.onGameEnded(score);
    }


 } 

由于某种原因,mListener始终为null。我在SO上尝试了其他问题,但没有一个有效。我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为你必须在 GameFragment

中覆盖这两个方法
  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (activity instanceof Listener ) {
      mListener = (Listener) activity;
    } else {
      throw new ClassCastException(activity.toString()
          + " must implemenet GameFragment.Listener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener= null;
  }

了解更多详情阅读此Tutorial

修改

不要忘记在活动中初始化片段

      // Create an instance of GameFragment
        GameFragment mGameFragment= new GameFragment();


        // Add the fragment to the 'fragment_container' Layout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, mGameFragment).commit();