编程语言
首页 > 编程语言> > java-我在onAttach(Context)中遇到了这个奇怪的错误

java-我在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

注意:

在api 23中添加了onAttach(Context context).请参见this

标签:eclipse,android-context,android-activity,java,android
来源: https://codeday.me/bug/20191118/2031943.html