简体   繁体   English

无法访问公共无效方法

[英]Can't access public void method

I have this method in my RecyclerView.Adapter 我的RecyclerView.Adapter有此方法

public void filter(String text) {
    mDataSet.clear();
    if(text.isEmpty()){
        mDataSet.addAll(mDataSet);
    } else{
        text = text.toLowerCase();
        for(AppInfo item: mDataSet){
            if(item.getAppName().toLowerCase().contains(text)){
                mDataSet.add(item);
            }
        }
    }
    notifyDataSetChanged();
}

and I'm trying to access it from my Activity by calling: 我正在尝试通过以下方式从我的Activity访问它:

search_view.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            //Here is where I'm trying to call the method
            mAdapter.filter(query);
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return true;
        }
    });

But for some reason I can't access the method. 但是由于某种原因,我无法访问该方法。 Can someone please explain to me why that is? 有人可以向我解释为什么吗?

You've declared mAdapter as a RecyclerView.Adapter , so you can only access the methods declared in RecyclerView.Adapter , not your custom class. 您已将mAdapter声明为RecyclerView.Adapter ,因此您只能访问RecyclerView.Adapter声明的方法,而不能访问自定义类。 As an example, let's say you have two classes: 例如,假设您有两个类:

public class Adapter {
    public void firstMethod() {}
}

public class ExtendedAdapter extends Adapter {
    public void secondMethod() {}
}
  • If you declare mAdapter as an instance of Adapter , you'll only be able to call firstMethod() as the compiler is only aware of that method. 如果将mAdapter声明为Adapter的实例,则只能调用firstMethod()因为编译器仅知道该方法。
  • However, if you declare mAdapter to be an instance of ExtendedAdapter , you'll be able to access firstMethond() by inheritance, as well as secondMethod() which only belongs to ExtendedAdapter . 但是,如果将mAdapter声明为ExtendedAdapter的实例,则可以通过继承访问firstMethond()以及仅属于ExtendedAdapter secondMethod()

So basically you need to declare mAdapter as an instance of the class that extends RecyclerView.Adapter , whatever you may have called it. 因此,基本上,您需要将mAdapter声明为扩展RecyclerView.Adapter的类的实例,无论您如何调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM