我在 onAttach(Context) 中收到这个奇怪的错误

I am getting this strange error on in onAttach(Context)

onAttach 函数中,eclipse 显示错误

The method onAttach(Activity) in the type Fragment is not applicable for the arguments (Context)

虽然明明是传递的Context类型变量

import android.content.Context;

public class MyListFragment extends Fragment{
    private OnItemSelectedListener listener;

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rsslist_overview,
            container, false);
        Button button = (Button) view.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            updateDetail("fake");
          }
        });
        return view;
      }

      public interface OnItemSelectedListener {
        public void onRssItemSelected(String link);
      }

      @Override
      public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnItemSelectedListener) {
          listener = (OnItemSelectedListener) context;
        } else {
          throw new ClassCastException(context.toString()
              + " must implemenet MyListFragment.OnItemSelectedListener");
        }
      }

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

      // may also be triggered from the Activity
      public void updateDetail(String uri) {
        // create a string just for testing
        String newTime = String.valueOf(System.currentTimeMillis());

        // inform the Activity about the change based
        // interface defintion
        listener.onRssItemSelected(newTime);
      }
}

如果您使用 API < 23 那么

public void onAttach(Context context) {

应该是

public void onAttach(Activity context) {

official docs

注:

onAttach(Context context) 已添加到 api 23。参见 this

我遇到了同样的问题,你能尝试像这样在你的 onAtach 方法中传递 Activity 吗:

   @Override
      public void onAttach(Activity activity) {
        super.onAttach(context);
        if (context instanceof OnItemSelectedListener) {
          listener = (OnItemSelectedListener) activity;
        } else {
          throw new ClassCastException(context.toString()
              + " must implemenet MyListFragment.OnItemSelectedListener");
        }
      }

然后告诉我它是否有效。 希望能帮到你!