Is not accessible in current context

后端 未结 4 1252
猫巷女王i
猫巷女王i 2021-02-05 04:58

I have the following code

public abstract class BaseAdapter extends ArrayAdapter {
    public BaseAdapter(Con         


        
4条回答
  •  猫巷女王i
    2021-02-05 05:51

    Here's how it got resolved for me. Generally there shouldn't be a circular dependency problem, as the nested viewholder classes are static. E.g. look at the notorious LayoutParams hierarchy, which is built exactly the same way: a class inherits another class and then their static nested classes have corresponding inheritance relationship.
    It looks like the circularity comes rather from the visibility scope issue. ModelViewHolder may extend ViewHolder only as it gets to know it after the outer ModelAdapter inherits BaseAdapter's visibility scope. Meanwhile ModelAdapter cannot inherit BaseAdapter until ModelViewHolder class is initialised as it needs for the generic parameter. On the other hand, ModelViewHolder is a static nested class and doesn't technically depend on its outer class.

    Thus, the solution is to fully qualify the ViewHolder's name when declaring ModelViewHolder. Note the extends BaseAdapter.ViewHolder part in the snippet below. This way, ModelViewHolder doesn't need to use ModelAdapter's scope to know about ViewHolder.

    ModelAdapter.java

    public class ModelAdapter extends BaseAdapter {
        public ModelAdapter(Context context, int resource, Collection collection) {
            super(context, resource, collection);
            // typical constructor logic
        }
    
        public static class ModelViewHolder extends BaseAdapter.ViewHolder {
            // custom defined logic
        }
    }
    

    A note about Android Studio: Even though the issue itself isn't related to Android Studio, I ran into it by using AS's "Copy class" feature (using AS 3.0). While copying, it "simplified" the code for me, removing the fully qualified name. So, watch out for AS's smartness!

提交回复
热议问题