如何在android中突出显示搜索/过滤的文本?

时间:2017-02-05 07:03:11

标签: android searchview

过滤文本工作正常但现在我的要求是用一些颜色突出显示过滤后的文本。如何在我的代码中实现这个

代码如下: 适配器类中的过滤器方法:

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ContestHolder> implements View.OnClickListener {
List<Student_model> data = new ArrayList<>();
List<Student_model> templist;
int expandedPosition = -1;
int prev = -2;
Context context;
student_fragment student_fragment;
Student_model contest;
String url = "http://labsls.com/drill/index.php/questionpool/deleteusers";

public class ContestHolder extends RecyclerView.ViewHolder {
    public TextView title, sub, school, name, password, username, email, phonenum, stdlvl, std, scl;
    public RelativeLayout details, titlebar;
    public Button update, home;
    public ImageView image, tick;
    EditText stdnmedi, useredi, passwordedi, emailedi, phoneedi, stndrdedi, schooledi;

    public ContestHolder(View v) {
        super(v);
        title = (TextView) v.findViewById(R.id.studenttitle);
        sub = (TextView) v.findViewById(R.id.standardsub);
        std = (TextView) v.findViewById(R.id.std);
        scl = (TextView) v.findViewById(R.id.skool);
        home = (Button) v.findViewById(R.id.homebt);
        details = (RelativeLayout) v.findViewById(R.id.detials);
        titlebar = (RelativeLayout) v.findViewById(R.id.titlebar);
        name = (TextView) v.findViewById(R.id.stdname);
        stdnmedi = (EditText) v.findViewById(R.id.namedi);
        useredi = (EditText) v.findViewById(R.id.ediuser);
        update = (Button) v.findViewById(R.id.updatebt);
        passwordedi = (EditText) v.findViewById(R.id.passuser);
        emailedi = (EditText) v.findViewById(R.id.ediemail);
        phoneedi = (EditText) v.findViewById(R.id.ediphone);
        stndrdedi = (EditText) v.findViewById(R.id.edistd);
        schooledi = (EditText) v.findViewById(R.id.edischoolz);
        tick = (ImageView) v.findViewById(R.id.imgtic);
    }
}

public StudentAdapter(Context context, List<Student_model> data, student_fragment student) {
    this.context = context;
    this.data = data;
    this.student_fragment = student;
    this.templist = new ArrayList<>(data);
}

@Override
public ContestHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_list, parent, false);
    ContestHolder holder = new ContestHolder(v);
    holder.titlebar.setOnClickListener(StudentAdapter.this);
    holder.titlebar.setTag(holder);
    return holder;
}

@Override
public void onBindViewHolder(final ContestHolder holder, final int position) {
    contest = data.get(position);
    holder.title.setText(contest.getTitle());
    holder.std.setText(" " + contest.getStdlevel());
    holder.scl.setText(" " + contest.getSchool());
    holder.stdnmedi.setText(contest.getTitle());
    holder.useredi.setText(contest.getUsername());
    holder.phoneedi.setText(contest.getPhonenum());
    holder.passwordedi.setText(contest.getPassword());
    holder.emailedi.setText(contest.getEmail());
    holder.stndrdedi.setText(contest.getStdlevel());
    holder.schooledi.setText(contest.getSchool());
    holder.home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, Landing.class));
        }
    });
    holder.titlebar.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View view) {
            data.get(position).setSelect(!data.get(position).isSelect());
            holder.tick.setVisibility(data.get(position).isSelect() ? View.VISIBLE : View.GONE);
            showremove();
            return true;
        }
    });
    holder.update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String ur = "http://labsls.com/drill/index.php/questionpool/updateuserdetails";
            StringRequest stringrequest = new StringRequest(Request.Method.POST, ur, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d("testup", response);
                    try {
                        JSONObject object = new JSONObject(response);
                        JSONArray array = object.getJSONArray("response");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject Objectz = array.getJSONObject(i);
                            String namee = Objectz.getString("fullname");
                            holder.stdnmedi.setText(namee);
                            String usere = Objectz.getString("username");
                            holder.useredi.setText(usere);
                            String passe = Objectz.getString("password");
                            holder.passwordedi.setText(passe);
                            String emaile = Objectz.getString("email_id");
                            holder.emailedi.setText(emaile);
                            String phonee = Objectz.getString("mobile");
                            holder.phoneedi.setText(phonee);
                            String stlvle = Objectz.getString("standardlevel");
                            holder.stndrdedi.setText(stlvle);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    //  params.put("nAme",holder.stdnmedi.getText().toString());
                    params.put("uName", holder.useredi.getText().toString());
                    params.put("pAwd", holder.passwordedi.getText().toString());
                    //  params.put("eMail",holder.emailedi.getText().toString());
                    params.put("mobile", holder.phoneedi.getText().toString());
                    params.put("school", holder.schooledi.getText().toString());
                    params.put("standardlevel", holder.stndrdedi.getText().toString());
                    params.put("uID", contest.getUseruniq());
                    return params;
                }
            };
            stringrequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(stringrequest);
            Toast.makeText(context, holder.stdnmedi.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    });
    if (position == expandedPosition) {
        holder.details.setVisibility(View.VISIBLE);
    } else {
        holder.details.setVisibility(View.GONE);
    }
}

public void filter(String query) {
    data.clear();
    Log.d("Test", "1");
    if (query.length() == 0) {
        data.addAll(templist);
    } else {
        String filterPattern = query.toLowerCase().trim();
        for (Student_model app : templist) {
            if (app.getTitle().toLowerCase().contains(filterPattern)) {
                data.add(app);
            }
        }
        notifyDataSetChanged();

    }
}

调用适配器类中的filter方法的类:

SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener(){
    @Override
    public boolean onQueryTextSubmit(String query){
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        adapter.filter(newText);
        return true;
    }
};

1 个答案:

答案 0 :(得分:1)

1. in StudentAdapter create global variable;
   String searchString="";
2. in method filter(String query), asign searchString=query;
3. in onBindViewHolder() method, put below code.



SpannableString spannableStringSearch = null;

if ((searchString!= null) && (!searchString.isEmpty())) {        
      spannableStringSearch = new SpannableString(contest.getTitle());
    Pattern pattern = Pattern.compile(searchString, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(contest.getTitle());
    while (matcher.find()) {
            spannableStringSearch.setSpan(new ForegroundColorSpan(
                            ContextCompat.getColor(context, R.color.red)),
            matcher.start(), matcher.end(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
if(spannableStringSearch !=null){
    holder.title.setText(spannableStringSearch);
}
else{
   holder.title.setText(spannableStringSearch);
}