活动中的SearchView和片段中的RecyclerView

时间:2019-01-18 11:25:17

标签: java android android-recyclerview searchview

在这里输入代码我尝试做一个演示,其中SearchView位于Activity上,而Activity包含ViewPager(Tablayout)中的片段。 这些片段包含recyclerView。 我想通过包含SearchView的活动在recyclerView中进行搜索。 怎么可能?

// MainActivity

 public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, IFragmentListener {

ViewPager viewPager;
TabLayout tab;
SearchView search;
PageAdapter adapter;
String newText;
ArrayList<String> listData = null;
ArrayList<ISearch> iSearch = new ArrayList<>();
IDataCallback iDataCallback = null;

public void setiDataCallback(IDataCallback iDataCallback) {
    this.iDataCallback = iDataCallback;
    iDataCallback.onFragmentCreated(listData);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewPager = findViewById(R.id.viewPager);
    tab = findViewById(R.id.tab);
    search = findViewById(R.id.search);
    listData = new ArrayList<>();

    tab.addTab(tab.newTab().setText("Tab1"));
    tab.addTab(tab.newTab().setText("Tab2"));
    tab.setTabGravity(TabLayout.GRAVITY_FILL);


    adapter = new PageAdapter(getSupportFragmentManager(), tab.getTabCount(), newText);

    viewPager.setAdapter(adapter);
    tab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });


}

@Override
public void addiSearch(ISearch iSearch) {
    this.iSearch.add(iSearch);
}

@Override
public void removeISearch(ISearch iSearch) {
    this.iSearch.remove(iSearch);
}

public void getDataFromFragment_one(ArrayList<String> listData) {
    this.listData = listData;
    Log.e("-->", "" + listData.toString());
}

@Override
public boolean onQueryTextSubmit(String s) {
    return false;
}

@Override
public boolean onQueryTextChange(String s) {
    this.newText = s;
    adapter.setTextQueryChanged(s);
    for (ISearch iSearchLocal : this.iSearch)
        iSearchLocal.onTextQuery(s);
    return true;
}

}

// RecyclerViewAdapter

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable {

private LayoutInflater inflater;
private List<Model> imageModelArrayList;
private List<Model> arraylist;

public Adapter(Context ctx, List<Model> imageModelArrayList){

    inflater = LayoutInflater.from(ctx);
    this.imageModelArrayList = imageModelArrayList;
    this.arraylist = new ArrayList<Model>();
    this.arraylist.addAll(Tab1.movieNamesArrayList);
}

@Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.rv_item, parent, false);
    MyViewHolder holder = new MyViewHolder(view);

    return holder;
}

@Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {

    holder.time.setText(imageModelArrayList.get(position).getName());
}

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

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                arraylist = imageModelArrayList;
            } else {
                List<Model> filteredList = new ArrayList<>();
                for (Model row : imageModelArrayList) {
                    if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getName().contains(charSequence)) {
                        filteredList.add(row);
                    }
                }

                arraylist = filteredList;
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = arraylist;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            arraylist = (ArrayList<Model>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}

class MyViewHolder extends RecyclerView.ViewHolder{

    TextView time;

    public MyViewHolder(View itemView) {
        super(itemView);

        time = itemView.findViewById(R.id.tv);
    }

}

}

// PagerAdapter

public class PageAdapter extends FragmentStatePagerAdapter {
private String mSearchTerm;
int tabCount;

public PageAdapter(FragmentManager fm, int tabCount, String searchTerm) {
    super(fm);
    this.tabCount= tabCount;
    this.mSearchTerm= searchTerm;
}
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            Tab1 tab1 = Tab1.newInstance(mSearchTerm);
            return tab1;
        case 1:
            Tab2 tab2 = Tab2.newInstance(mSearchTerm);
            return tab2;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return tabCount;
}

public void setTextQueryChanged(String newText) {
    mSearchTerm = newText;
}

}

//片段

public class Tab1 extends Fragment implements ISearch {
RecyclerView recylerView;
private static final String ARG_SEARCHTERM = "search_term";
private String mSearchTerm = null;
public static List<Model> movieNamesArrayList;
private IFragmentListener mIFragmentListener = null;
private List<Model> models = new ArrayList<>();
String[] nameArray = {"Birthday", "Party", "Wedding", "Holidays", "Thank You", "General", "Engagement","Retirement"};
LinearLayoutManager manager;
Adapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_tab1, container, false);
    recylerView = view.findViewById(R.id.recycler);
    manager = new LinearLayoutManager(getContext());
    movieNamesArrayList = populateList();
    adapter = new Adapter(getActivity(),models);
    recylerView.setLayoutManager(manager);
    recylerView.setAdapter(adapter);
    recylerView.addOnItemTouchListener(new RecyclerTouchListener(getContext(), recylerView, new ClickListener() {

        @Override
        public void onClick(View view, int position) {
            Toast.makeText(getContext(), movieNamesArrayList.get(position).getName(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));
    ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(nameArray));

    MainActivity mainActivity = (MainActivity) getActivity();
    mainActivity.getDataFromFragment_one(stringList);
    if (getArguments() != null) {
        mSearchTerm = (String) getArguments().get(ARG_SEARCHTERM);
    }

    addItems();
    return view;
}
private ArrayList<Model> populateList(){
    ArrayList<Model> list = new ArrayList<>();
    for(int i = 0; i < 8; i++){
        Model imageModel = new Model();
        imageModel.setName(nameArray[i]);
        list.add(imageModel);
    }

    return list;
}

@Override
public void onTextQuery(String text) {
    adapter.getFilter().filter(text);
    adapter.notifyDataSetChanged();
}

public void addItems(){
    for (int i = 0; i < nameArray.length; i++){
        Model inviteModel = new Model();
        inviteModel.setName(nameArray[i]);
        models.add(inviteModel);
        adapter.notifyDataSetChanged();

    }
}

public static Tab1 newInstance(String searchTerm) {
    Tab1 fragment = new Tab1();
    Bundle bundle = new Bundle();
    bundle.putString(ARG_SEARCHTERM, searchTerm);
    fragment.setArguments(bundle);
    return fragment;
}
public interface ClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final Tab1.ClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

@Override
public void onResume() {
    super.onResume();
    if (null != mSearchTerm) {
        onTextQuery(mSearchTerm);
    }
}

public Tab1() {
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mIFragmentListener = (IFragmentListener) context;
    mIFragmentListener.addiSearch(Tab1.this);
}

@Override
public void onDetach() {
    super.onDetach();
    if (null != mIFragmentListener)
        mIFragmentListener.removeISearch(Tab1.this);
}

}

//接口

public interface IDataCallback {
void onFragmentCreated(ArrayList<String> listData);

}

public interface IFragmentListener {

void addiSearch(ISearch iSearch);

void removeISearch(ISearch iSearch);

}

public interface ISearch {
void onTextQuery(String text);

}

0 个答案:

没有答案