RecyclerView: Inner classes cannot have static declaration

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

I am a little confused, I have setup a recyclerview as per the tutorial on google/android site and I get the following error

 Inner classes cannot have static declaration 

Of course I do have a nested static class but this is how android/google defined it.

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

Why i am geting this error, I hear its better to use nested class as a static so you are not wasting a reference but current version of android studio is complaining

Any ideas ?

Thanks

回答1:

Straight To Your Question :-

1. Inner classes cannot have static declaration 

That's completely true, its not a bug and not even the message is misleading.

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

You are absolutely correct.

3. Solution to You 

Create a new class(File) in your project for ItemsViewAdapter and there won't be such error.


General Discussion :

Java and Android both supports that you can declare Static inner class/member/function BUT that class should be parent class, you can not do that inside a Inner Class

i.e. class Main can have static class Adapter but if Adapter class is not static and still it's a inner class of Main then it can't have static inner class/member.

What You Can Have ?:

class Main     static class Adapter        static class Holder 

Or

 class Adapter            static class Holder 

If you want to declare any member of class as STATIC then the immediate OuterClass must be your Main Class in that file.


Why this ? :

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.


Sites To Visit :

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/



回答2:

You could also simply implement ItemViewAdapter as a static class

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

That should take care of the error



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!