简体   繁体   中英

Can't access public void method

I have this method in my 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:

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. 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.
  • 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 .

So basically you need to declare mAdapter as an instance of the class that extends RecyclerView.Adapter , whatever you may have called it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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