在ViewPager中从片段调用适配器

时间:2016-05-24 11:53:41

标签: android android-fragments android-viewpager android-recyclerview

我有片段,它有一个searchview和viewpager。我的viewpager有3个片段和每个片段调用适配器。现在要实现searchview,我需要在view pager中调用可见片段的适配器。

SlidingTab(带有searchview和ViewPager的片段):

public class SlidingTab extends Fragment {
    private static final String TAG = "TabLayout";
    private static String POSITION = "POSITION";
    private Context context;
    private SearchView searchview;
    private Toolbar toolbar ;


    /*searching/filteration query*/
    private SearchView.OnQueryTextListener OnQuerySearchView = new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String arg0) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onQueryTextChange(String arg0) {
            // TODO Auto-generated method stub
//            if (searchCheck) {
            Log.i("Recycler query", arg0);

//            Fragment frag = new PageAdapter(getChildFragmentManager(),context).getItem(viewPager.getCurrentItem());
            PageAdapter adapter = ((PageAdapter) viewPager.getAdapter());
            Fragment fragment = adapter.getFragment(viewPager.getCurrentItem());
            return false;
        }
    };

    public SlidingTab() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.sliding_tab, container, false);
         viewPager = (ViewPager) v.findViewById(R.id.view_pager);
        viewPager.setOffscreenPageLimit(2);
        viewPager.setAdapter(new PageAdapter(getChildFragmentManager(), context));
        slidingTab = (TabLayout) v.findViewById(R.id.sliding_tabs);
        searchview = (SearchView)v.findViewById(R.id.searchView);
        searchview.setOnQueryTextListener(OnQuerySearchView);
        return v;
    }

SlidingTab.class(实施SearchView)

public class PageAdapter extends FragmentStatePagerAdapter {
    private static final String TAG = "PageAdapter";
    final int PAGE_COUNT = 3;
    private String tabTitles[] = new String[]{"New", "In Progress", "Completed"};
    private Context context;

    public PageAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }


    @Override
    public Fragment getItem(int position) {
        Log.d(TAG, "New Instance Created :" + position);
        switch (position) {
            case 0:
                return new JobFragment();

            case 1:
                return new InProgressJobFragment();
            case 2:
                return new CompletedJobFragment();
        }
        return null;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }


}

PageAdapter.class

public class JobAdapter extends RecyclerView.Adapter<JobAdapter.ViewHolder> {
    private static final String TAG = "EMPLOYEE ADAPTER";
    private static final int VIEW_NORMAL = 0;
    private ArrayList<Info> mDataset;
    private ArrayList<Info> filterList;
    private Context mAct;

    public class ViewHolder extends RecyclerView.ViewHolder {

        }
    }

    public void addApplications(ArrayList<Info> candidates) {
      }

    public void clearApplications() {
     }

    public JobAdapter(ArrayList<Info> myDataset, Context context) {
        this.mDataset = myDataset;
        this.mAct = context;
    }



    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.job_card_new, parent, false);
        ViewHolder fh = new ViewHolder(v);
        return fh;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

//      }



**//    *searching/filtration on List*/**
    public void filter(String charText) {
        filterList.clear();
        if (charText.length() == 0) {
            if(mDataset != null) {
                filterList.addAll(mDataset);
            }
        } else {
            if (mDataset != null){
                for (Info wp : mDataset) {
                    if(wp.jobNumber !=null){
                        if(Pattern.compile(Pattern.quote(charText), Pattern.CASE_INSENSITIVE).matcher(wp.jobNumber).find()){
//                    if (wp.heading1.toLowerCase().contains(charText.toLowerCase())) {
                            filterList.add(wp);
                        }}else{

                    }

                    this.notifyItemRangeRemoved(0, filterList.size());

                }
            }
        }
        notifyDataSetChanged();
    }


    @Override
    public int getItemCount() {
        return mDataset.size();
    }
}

片段RecyclerView适配器(由视图寻呼机中的每个片段调用并具有searchview过滤方法)

{{1}}
  

请帮我在viewpager中实现searchview。

2 个答案:

答案 0 :(得分:3)

借助上传的代码 我可以告诉你

在你的片段中创建名为search的方法 呼叫适配器过滤方法

public void search(String text)
{
adapter.filter(text)
}

您可以在此行之后检查片段的实例并调用片段的搜索方法

 Fragment fragment = adapter.getFragment(viewPager.getCurrentItem());

答案 1 :(得分:0)

我认为最好的设计是使用Activity作为需要分段的事件的中心“中心”。

所以这就是我要这样做的方式:

  • 首先从侦听器界面开始。这可以声明为Activity

    的内部接口
    static interface QueryListener {
    
        void onQueryChange(String query);
    }
    
  • Activity获取用于保存侦听器的属性以及用于添加和删除侦听器的方法(声明为synchronized以防止那些令人讨厌的ConcurrentModificationException

    private List<QueryListener> mQueryListeners = new ArrayList<>();
    
    public synchronized void addQueryListener(@NonNull QueryListener listener) {
    
       // check if the listener was already added
       // you could also use a Set instead of a List for this
       if (mQueryListeners.contains(listener)) return;   
    
       mQueryListeners.add(listener);
    }
    
    public synchronized void removeQueryListener(@NonNull QueryListener listener) {
        mQueryListeners.remove(listener);
    }
    
  • Activity也会获得一个方法,可以通过SearchView的片段调用:

    public synchronized void changeQuery(String query) {
    
            for (QueryListener listener : mQueryListeners) {
                listener.onQueryChange(query);
            }
    }
    
  • 现在使用适配器的片段需要实现QueryListener并注册/取消注册:

    onCreate()中的某处添加此行:

            ((YourActivity) getActivity()).addQueryListener(this);
    

    取消注册onDestroy()

        @Override
        public void onDestroy() {
            ((YourActivity) getActivity()).removeQueryListener(this);
            super.onDestroy();
        }
    

    添加QueryListener方法实现:

    @Override
    public void onQueryChange(String query) {
    
        // if (isVisible()) {      if desired
        mAdapter.filter(query);
    }
    

    注意:您不必拥有片段实现QueryListener;你可以使用匿名类。但是您必须保留对它的引用,以便稍后可以使用它来调用removeQueryListener()

  • 现在只需挂上SearchView

    @Override
    public boolean onQueryTextChange(String query) {
    
        ((YourActivity) getActivity()).changeQuery(query);
    }
    

我使用的另一种模式是创建一个用于注册/通知侦听器的专用类。我创建了这个类的单个实例,并在Activity上有一个方法来访问它:

        QueryHandler handler = ((YourActivity) getActivity()).getQueryHandler();
        // QueryHandler has all the listener properties and methods shown for the Activity

        ...

        handler.changeQuery(query);

或者,您也可以使用Otto等众多开源事件总线包之一在您的片段中传递事件。