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

标签 java android eclipse android-activity android-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

关于java - 我在 onAttach(Context) 中收到这个奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36058226/

相关文章:

android - 当其他用户登录Android时如何从 Realm 中删除用户数据

android - 在运行时将行和键添加到 android 中的自定义键盘

eclipse - 在(引用的)Web 项目中找不到引用的 EJB 项目的类

eclipse - org.apache.tomcat.util.bcel.classfile.ClassFormatException : Invalid byte tag in constant pool: 15

java - 使用三元运算符时出错

java - NetworkDispatcher.run : Unhandled exception java. lang.SecurityException : Permission denied (missing INTERNET permission?)

java - 将 Activiti 任务从旧流程迁移到新流程

java - 无法通过 Docker 创建与数据库服务器的连接

java - 在 Java 中导入 CSV 文件

java - 将 jar 导入 android 应用程序