How to implement searchmenu in a fragment?

无人久伴 提交于 2020-03-22 23:19:02

问题


I followed this video: https://codinginflow.com/tutorials/android/searchview-recyclerview

This is my fragment which is like MainActivity :

public class cgpa_frag extends Fragment {

RecyclerView recyclerview;
adapter_cgpa ac;

ArrayList<POJO> cgpaArrayList = new ArrayList<>();

public cgpa_frag() {
    // Required empty public constructor
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_cgpa_frag, container, false);
    recyclerview = (RecyclerView) view.findViewById(R.id.rc2);
    cgpaArrayList = new ArrayList<>();
    ac = new adapter_cgpa(cgpaArrayList);
    recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
    recyclerview.setAdapter(ac);


    Fetchdata2();
    return view;
}

private void Fetchdata2() {
    dbmanager db = new dbmanager(getContext());

    Cursor cursor = db.fetch_data2();

    if (cursor != null) {

        // cursor.moveToFirst();
        while (cursor.moveToNext()) {

            POJO pj = new POJO();
            pj.setCname(cursor.getString(0));
            pj.setNo_of_sems(cursor.getString(1));
            pj.setCgpa(cursor.getString(2));
            pj.setPercentage(cursor.getString(3));
            pj.setSchemec(cursor.getString(4));
            cgpaArrayList.add(pj);
        }

        ac = new adapter_cgpa(cgpaArrayList);


    }

}

@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    inflater.inflate(R.menu.search_menu, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            ac.getFilter().filter(newText);
            return false;

        }
    });
}

}

This is my adapter class:

public class adapter_cgpa extends RecyclerView.Adapter<adapter_cgpa.Viewholder> implements Filterable {

    ArrayList<POJO> cgpaArrayList;
    ArrayList<POJO> cgpaArrayListcopy;

    public adapter_cgpa(ArrayList<POJO> cgpaArrayList) {
        this.cgpaArrayList = cgpaArrayList;
        cgpaArrayListcopy = new ArrayList<>(cgpaArrayList);
    }

    @NonNull
    @Override
    public adapter_cgpa.Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View listitem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cgpa, parent, false);
        return new Viewholder(listitem);
    }

    @Override
    public void onBindViewHolder(@NonNull adapter_cgpa.Viewholder holder, int position) {
        POJO cgpa= cgpaArrayList.get(position);
        holder.cname.setText(cgpa.getCname());
        holder.no_of_sems.setText(cgpa.getNo_of_sems());
        holder.cgpa.setText(cgpa.getCgpa());
        holder.percentage.setText(cgpa.getPercentage());
        holder.schemec.setText(cgpa.getSchemec());
    }
    @Override
    public int getItemCount() {
        return cgpaArrayList.size();
    }

    @Override
    public Filter getFilter() {
        return exampleFilter;
    }

    private Filter exampleFilter = new Filter() {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<POJO>filteredList=new ArrayList<>();

            if(constraint==null || constraint.length()==0){
                filteredList.addAll(cgpaArrayListcopy);
            }
            else {
                String filterPattern = constraint.toString().toLowerCase().trim();
                for( POJO item : cgpaArrayListcopy){
                    if (item.getCname().toLowerCase().contains(filterPattern)){
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results=new FilterResults();
            results.values=filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            cgpaArrayList.clear();
            cgpaArrayList.addAll((List)results.values);
            notifyDataSetChanged();
        }
    };

    public class Viewholder extends RecyclerView.ViewHolder {
        TextView cname, no_of_sems, cgpa, percentage,schemec;
        ImageButton btndelete2;
        public Viewholder(@NonNull View itemView) {
            super(itemView);
            cname=(TextView)itemView.findViewById(R.id.name);
            no_of_sems=(TextView)itemView.findViewById(R.id.no_of_sem);
            cgpa=(TextView)itemView.findViewById(R.id.textView49);
            percentage=(TextView)itemView.findViewById(R.id.textView55);
            schemec=(TextView)itemView.findViewById(R.id.scheme2);
            btndelete2=(ImageButton)itemView.findViewById(R.id.btndelete2);
            btndelete2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                    alert.setMessage("Are you sure you want to delete this?");

                            alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    });
                    alert.setPositiveButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    });
                    final AlertDialog dialogs  = alert.create();
                    dialogs.show();
                    dialogs.getButton(androidx.appcompat.app.AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            delete(getAdapterPosition());
                            dialogs.dismiss();

                        }
                    });
                    dialogs.getButton(androidx.appcompat.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            dialogs.dismiss();
                        }
                    });

                }
            });
        }

        private void delete(int adapterPosition) {

            cgpaArrayList.remove(adapterPosition);
            notifyDataSetChanged();
            final String snc = cname.getText().toString();
            final String semrc = no_of_sems.getText().toString();
            final String schc = schemec.getText().toString();

            dbmanager db = new dbmanager(itemView.getContext());
            db.delete2(snc, semrc, schc);
        }
    }
}

This is search_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:title="Search by name..."
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.widget.SearchView" />

</menu>

When I am running the app, I cannot see any search option. Can anyone suggest me the changes I need to make in my code. Or where am I going wrong?


回答1:


Just add SearchView before RecyclerView, and configurate it




回答2:


See this page, I think it is what you want: https://demonuts.com/kotlin-recyclerview-searchview/

It has searchview used in recyclerview.



来源:https://stackoverflow.com/questions/60735312/how-to-implement-searchmenu-in-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!