0

In the below code I have a Search feature like Whatsapp application. Now When I am searching a text it is giving me a pinpoint result. After that result I am trying to highlight the text after the search is complete.

But it is not working with my code.

For example: if my search text is abc, I want to highlight abc with different text color with bold.

Fragment:

public void setSearchtollbar()
    {
        searchtollbar = (androidx.appcompat.widget.Toolbar) getActivity().findViewById(R.id.searchtoolbar);
        if (searchtollbar != null) {
            searchtollbar.inflateMenu(R.menu.menu_search);
            search_menu=searchtollbar.getMenu();

            searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                        circleReveal(R.id.searchtoolbar,1,true,false);
                    else
                        searchtollbar.setVisibility(View.GONE);
                }
            });

            item_search = search_menu.findItem(R.id.action_filter_search);

            MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
                @Override
                public boolean onMenuItemActionCollapse(MenuItem item) {
                    // Do something when collapsed
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        circleReveal(R.id.searchtoolbar,1,true,false);
                    }
                    else
                        searchtollbar.setVisibility(View.GONE);
                    return true;
                }

                @Override
                public boolean onMenuItemActionExpand(MenuItem item) {
                    // Do something when expanded
                    return true;
                }
            });

            initSearchView();


        } else
            Log.d("toolbar", "setSearchtollbar: NULL");
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.search);
        item.setVisible(true);
    }
    public void initSearchView()
    {
        final SearchView searchView =
                (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();

        searchView.setSubmitButtonEnabled(false);
        ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
        closeButton.setImageResource(R.drawable.ic_close_black_24dp);

        // set hint and the text colors
        EditText txtSearch = ((EditText) searchView.findViewById(R.id.search_src_text));
        txtSearch.setHint("Search..");
        txtSearch.setHintTextColor(Color.DKGRAY);
        txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));

        // set the cursor
        AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(R.id.search_src_text);
        try {
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
        } catch (Exception e) {
            e.printStackTrace();
        }

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                callSearch(query);
                searchView.clearFocus();
                return true;
            }

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

            public void callSearch(String query) {
                query = query.toLowerCase();
                Log.i("query", "" + query);
                onSearch(query);
            }

        });
    }
    // < ---- Implementing Search ends here ---- > //
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
    {
        final View myView = getActivity().findViewById(viewID);

        int width=myView.getWidth();

        if(posFromRight>0)
            width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
        if(containsOverflow)
            width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);

        int cx=width;
        int cy=myView.getHeight()/2;

        Animator anim;
        if(isShow)
            anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
        else
            anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);

        anim.setDuration((long)220);

        // make the view invisible when the animation is done
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(!isShow)
                {
                    super.onAnimationEnd(animation);
                    myView.setVisibility(View.INVISIBLE);
                }
            }
        });

        // make the view visible and start the animation
        if(isShow)
            myView.setVisibility(View.VISIBLE);

        // start the animation
        anim.start();


    }

    public static CharSequence highlightText(String search, String originalText) {
        if (search != null && !search.equalsIgnoreCase("")) {
            String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
            int start = normalizedText.indexOf(search);
            if (start < 0) {
                return originalText;
            } else {
                Spannable highlighted = new SpannableString(originalText);
                while (start >= 0) {
                    int spanStart = Math.min(start, originalText.length());
                    int spanEnd = Math.min(start + search.length(), originalText.length());
                    highlighted.setSpan(new ForegroundColorSpan(Color.BLUE), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    start = normalizedText.indexOf(search, spanEnd);
                }
                return highlighted;
            }
        }
        return originalText;
    }

Adapter.java:

public class TaskAdapter extends RecyclerSwipeAdapter<TaskAdapter.MyViewHolder> implements Filterable {

    private LayoutInflater inflater;
    private Context mContext;
    private ArrayList<TaskModel> tasklist;
    private ArrayList<TaskModel> mFilteredList;

    public boolean isClickable = true;
    private MyItemClickListener clickListener;
    private MyEditItemClickListner editItemClickListner;


    public TaskAdapter(Context context, ArrayList<TaskModel> tasklist, MyItemClickListener clickListener, MyEditItemClickListner editItemClickListner) {
        mContext=context;
        this.tasklist=tasklist;
        this.clickListener = clickListener;
        this.mFilteredList=tasklist;
        this.editItemClickListner=editItemClickListner;
    }

    @Override
    public TaskAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.fragment_task, parent, false);
        TaskAdapter.MyViewHolder holder = new TaskAdapter.MyViewHolder(view);
        return holder;
    }

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

        holder.subject.setText(tasklist.get(position).getSubject());
        holder.task_type.setText(tasklist.get(position).getTaskType());
        holder.assigned_to.setText(tasklist.get(position).getAssigned());
        holder.related_to.setText(tasklist.get(position).getParent_id());
        holder.outcome.setText(tasklist.get(position).getOutcome());
        holder.status.setText(tasklist.get(position).getStatus());
        holder.location.setText(tasklist.get(position).getLocation());
        holder.schedule_date.setText(tasklist.get(position).getScheduleDate());
        holder.schedule_date.setBackgroundResource(R.color.password);
        holder.opportunity.setText(tasklist.get(position).getOpportunityNo());
        // holder.createdtime.setText(tasklist.get(position).getCreatedtime());//okay where you need your api respnose from preferfernce.//ok
//        holder.subject.setText(subject);
//        holder.task_type.setText(task_type);
//        holder.assigned_to.setText(assigned_to);
//        holder.outcome.setText(outcome);
//        holder.status.setText(status1);
//        holder.location.setText(location);
//        holder.schedule_date.setText(schedule_date);
//        holder.opportunity.setText(opportunity);
        final String status = tasklist.get(position).getStatus();
        final String outcomes=tasklist.get(position).getOutcome();


        if(outcomes.equals(" Follow-up ")){
            holder.image.setImageResource(R.drawable.followup);
            holder.image.setColorFilter(ContextCompat.getColor(mContext, R.color.linecolor));
        }else if(outcomes.equals(" Order Closed ")){
            holder.image.setImageResource(R.drawable.orderclosed);
            holder.image.setColorFilter(ContextCompat.getColor(mContext, R.color.linecolor));
        }else if(outcomes.equals(" Interested ")){
            holder.image.setImageResource(R.drawable.ic_thumb_up_black_24dp);
        }else if(outcomes.equals(" Done ")){
            holder.image.setImageResource(R.drawable.done);
            holder.image.setColorFilter(ContextCompat.getColor(mContext, R.color.linecolor));
        }else if(outcomes.equals(" Collected ")){
            holder.image.setImageResource(R.drawable.collected);
            holder.image.setColorFilter(ContextCompat.getColor(mContext, R.color.linecolor));
        }else if(outcomes.equals(" Not Interested ")){
            holder.image.setImageResource(R.drawable.ic_thumb_down_black_24dp);
        }

        if(status.equals("Scheduled")){
            holder.status.setBackgroundResource(R.color.blue);
        } else if(status.equals("Completed")){
            holder.status.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green));
        } else if(status.equals("In Complete")){
            holder.status.setBackgroundResource(R.color.red);
        }

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("TASK ADAPTER", "onClick: Cardview");
                clickListener.myItemClick(position);
            }
        });


        holder.sample1.setShowMode(SwipeLayout.ShowMode.PullOut);
        holder.sample1.setDragEdge(SwipeLayout.DragEdge.Right);
//        sample2.setShowMode(SwipeLayout.ShowMode.PullOut);
        holder.sample1.findViewById(R.id.edit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editItemClickListner.myEditItemClick(position);
            }
        });

        holder.sample1.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(mContext, "Share", Toast.LENGTH_SHORT).show();
//                Intent sendIntent = new Intent();
//                sendIntent.setAction(Intent.ACTION_SEND);
//                sendIntent.putExtra(Intent.EXTRA_TEXT,true);
//                sendIntent.setType("text/plain");
//                Intent.createChooser(sendIntent,"Share via");
//                mContext.startActivity(sendIntent);
                Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
                whatsappIntent.setType("text/plain");
                whatsappIntent.setPackage("com.whatsapp");

                Intent email = new Intent(Intent.ACTION_SEND);
                email.putExtra(Intent.EXTRA_SUBJECT, "subject");
                email.putExtra(Intent.EXTRA_TEXT, "text");
                Uri uri = Uri.parse("file://" + email.getAction());
                email.putExtra(Intent.EXTRA_STREAM, uri);
                email.setType("message/rfc822");
                mContext.startActivity(email);
                whatsappIntent.putExtra(Intent.EXTRA_TEXT, "The text you wanted to share");
                try {
                    mContext.startActivity(whatsappIntent);
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(mContext,"Whatsapp have not been installed.",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public int getItemCount() {

        return tasklist.size();
    }


    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.sample1;
    }

    public void clear() {
        int size = tasklist.size();
        tasklist.clear();
        notifyItemRangeRemoved(0, size);
    }

    @Override
    public Filter getFilter() {

        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {

                    mFilteredList = tasklist;
                } else {

                    ArrayList<TaskModel> filteredList = new ArrayList<>();

                    for (TaskModel taskModel : tasklist) {

                        if (taskModel.getAssigned().toLowerCase().contains(charString) || taskModel.getParent_id().toLowerCase().contains(charString)) {

                            filteredList.add(taskModel);

                        }
                    }

                    mFilteredList = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = mFilteredList;
                return filterResults;
            }

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



    class MyViewHolder extends RecyclerView.ViewHolder{

        SwipeLayout sample1;
        TextView subject,outcome, status,task_type,assigned_to,related_to,schedule_date,location,opportunity,bill_pin,textViewOptionscreatedtime,modifiedtime,modifiedby,remark,activitytype,textViewOptions,createdtime;
        ImageView image;
        CardView cardView;
        ImageView share,tvEdit;
        LinearLayout cards;


        public MyViewHolder(View itemView) {
            super(itemView);
            sample1 = (SwipeLayout) itemView.findViewById(R.id.sample1);
            subject= (TextView) itemView.findViewById(R.id.subject);
            outcome = (TextView) itemView.findViewById(R.id.outcome);
            status = (TextView) itemView.findViewById(R.id.status);
            task_type = (TextView) itemView.findViewById(R.id.task_type);
            assigned_to = (TextView) itemView.findViewById(R.id.assigned_to);
            related_to = (TextView) itemView.findViewById(R.id.related_to);
            schedule_date = (TextView) itemView.findViewById(R.id.schedule_date);
            location = (TextView) itemView.findViewById(R.id.location);
            opportunity = (TextView) itemView.findViewById(R.id.opp_no);
            textViewOptions=(TextView)itemView.findViewById(R.id.textViewOptions);
            image=(ImageView)itemView.findViewById(R.id.image);
            share = (ImageView) itemView.findViewById(R.id.share);
            tvEdit = (ImageView) itemView.findViewById(R.id.edit);
            cardView = itemView.findViewById(R.id.cardView);
            // createdtime = (TextView) itemView.findViewById(R.id.createdtime);
//            modifiedtime = (TextView) itemView.findViewById(R.id.modifiedtime);
//            modifiedby = (TextView) itemView.findViewById(R.id.modifiedby);
//            activitytype=(TextView) itemView.findViewById(R.id.activitytype);
           // cards = (LinearLayout) itemView.findViewById(R.id.cards);


        }


    }


}
Stidgeon
  • 2,673
  • 8
  • 20
  • 28
jyo srijyo
  • 53
  • 6
  • Please don't repeat questions. Simply editing your original post with any new information you have, or any new code you've tried, will bump it to the top of the active queue. – Mike M. May 11 '20 at 18:50
  • @MikeM.how you will close the questiom,I didnot get the answer – jyo srijyo May 11 '20 at 19:18
  • Yeah, I know, but as I've told you before, this isn't the kind of site where you just keep reposting your questions. We're trying to build a repository of quality questions and answers that are easy to find, and useful to future users, and having a single problem spread out over multiple posts is not conducive to that. Your original question is still open, and these two recent ones point directly to it, so users can answer there, if they'd like to help. You haven't lost any visibility, here. – Mike M. May 11 '20 at 19:23

0 Answers0