本文介绍了RecyclerView:内部类不能有静态声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,我根据google / android网站上的教程设置了recyclerview,我收到以下错误

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

当然我有一个嵌套的静态类,但这是android / google如何定义它。

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 {
           ...
       }

为什么我要解决这个错误,我听说最好使用嵌套类作为静态,这样你就不会浪费一个参考但是当前版本的android studio抱怨

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

任何想法?

谢谢

推荐答案

直接提出问题:


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

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

你是绝对正确的。

解决方案:

在项目中为 ItemsViewAdapter 创建一个新类(File)不会出现这样的错误。

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






一般讨论

Java和Android都支持你可以声明 static 内部类/成员/函数, 但是该类应该是父类。你不能在内部类中做到这一点。

Java and Android both supports that you can declare static inner classes/members/functions, BUT that class should be a parent class. You cannot do that inside an inner class.

即, class Main 可以有 static class Adapter 但是如果 Adapter 类是内部类不是静态的那么它不能有自己的静态内部类/成员。

I.e., class Main can have static class Adapter but if the Adapter class is an inner class of Main is not static then it can't have its own static inner class/member.

你能拥有什么?

class Main
    static class Adapter
        static class Holder

class Adapter
    static class Holder

如果您要将类的任何成员声明为 static ,那么直接父级class必须是该文件中的顶级主要类。

If you want to declare any member of class as static then the immediate parent class must be the top-level, main class in that file.

为什么?

引用另一个答案,

进一步阅读主题

1

2

3

这篇关于RecyclerView:内部类不能有静态声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 20:52
查看更多