RecyclerView: 内部 类 不能有静态声明

RecyclerView: Inner classes cannot have static declaration

我有点困惑。我按照 google/android 网站上的教程设置了 RecyclerView,但出现以下错误:

 Inner classes cannot have static declaration

当然,我确实有一个嵌套静态 class 但这是 android/google 定义它的方式。

  public class ItemsViewAdapter extends RecyclerView.Adapter<ItemsViewAdapter.ViewHolder> {
       // ... 
       // ...
       public static class ViewHolder extends RecyclerView.ViewHolder {
           // ...
       }

为什么会出现此错误?我听说最好将 static 用于嵌套 classes,这样你就不会浪费参考,但 android studio 的当前版本正在抱怨

有什么想法吗?

直接回答您的问题:

  1. Inner classes cannot have static declaration

    完全正确。这不是错误,错误消息甚至没有误导性。

  2. I hear its better to use nested class as a static so you are not wasting a reference

    你完全正确。

  3. 您的解决方案:

    在你的项目中为ItemsViewAdapter新建一个class(文件),就不会出现这样的错误了。


一般性讨论

Java 和 Android 都支持你可以声明 static inner classes/members/functions, BUT that class 应该是 parent class。您不能在内部 class.

中执行此操作

class Main 可以有 static class Adapter 但如果 Adapter class 是 Main 的内部 class 则不是静态的它不能有自己的静态内部 class/member.

你能拥有什么?

class Main 
    static class Adapter
        static class Holder

class Adapter
    static class Holder

如果要将 class 的任何成员声明为 static,则直接 parent class 必须是 top-level,main class 在该文件中。

为什么?

引用另一个答案,It's because an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.

关于该主题的进一步阅读

1 http://www.geeksforgeeks.org/inner-class-java/

2 http://www.javaworld.com/article/2077372/learn-java/static-class-declarations.html

3 http://viralpatel.net/blogs/inner-classes-in-java/

您也可以简单地将 ItemViewAdapter 实现为静态 class

public static class ItemsViewAdapter extends RecyclerView.Adapter<ItemsViewAdapter.ViewHolder> {
    ... 
    ...
   public static class ViewHolder extends RecyclerView.ViewHolder {
       ...
   }

这应该可以解决错误