在 Listview 中搜索,并在 Listview 中突出显示搜索文本颜色 Android

Searching in Listview with searched textcolor highlighted in Listview Android

我有一个 listviewarrayadapter ..我需要在我的音乐应用程序中实现它...帮帮我

    public class Search_Class extends Activity {

        EditText searchedit;
        ListView listview3;
        SongsManager songManager;
        Context context;
        String[] abc;
        ArrayList<String> names;
        ArrayList<String> arrayList;
        ArrayAdapter<String> ad;
        private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.my_search);
            context = getBaseContext();
            searchedit = (EditText) findViewById(R.id.searchedit);
            listview3 = (ListView) findViewById(R.id.listview3);
            songManager = new SongsManager();
            songsList = songManager.getPlayList(context);
            names = new ArrayList<String>();
            arrayList = new ArrayList<String>();

            for (int i = 0; i < songsList.size(); i++) {
                HashMap<String, String> obj = songsList.get(i);

                names.add(obj.get("songTitle"));
                arrayList.add(obj.get("songTitle"));
            }

            abc = new String[names.size()];
            abc = names.toArray(abc);

            listview3.setTextFilterEnabled(true);

            // ad = new ArrayAdapter<String>(MySearch.this,
            // android.R.layout.simple_list_item_1, abc);
            // listview3.setAdapter(ad);
            listview3.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting listitem index

                    String[] abc1 = new String[arrayList.size()];
                    abc1 = arrayList.toArray(abc);

                    int songIndex;

                    for (int i = 0; i < abc1.length; i++) {
                        if (abc[position].equalsIgnoreCase(abc1[i])) {
                            songIndex = i;
                            Intent in = new Intent(Search_Class.this,
                                    MainActivity.class);
                            // Sending songIndex to PlayerActivity
                            SharedPreferences sp;
                            sp = getSharedPreferences("lastplayed", MODE_PRIVATE);
                            Editor edit = sp.edit();
                            edit.putBoolean("searchSongIndex", true);
                            edit.commit();
                            in.putExtra("songIndex", songIndex);

                            in.putExtra("FLAG", true);
                            startActivity(in);
                            finish();

                            break;
                        }
                    }

                }

            });
            // ad.notifyDataSetChanged();

            searchedit.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                        int arg3) {
                    // TODO Auto-generated method stub
                    // MySearch.this.ad.getFilter().filter(arg0);

                    String text = arg0.toString().toLowerCase(Locale.getDefault());
                    filter(text);

                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub

                }
            });

        }

        public void filter(String charText) {
            System.out.println("Text---" + charText);
            charText = charText.toLowerCase(Locale.getDefault());
            names.clear();
            if (charText.length() == 0) {
                System.out.println("if---" + arrayList.size());
                abc = new String[arrayList.size()];
                abc = arrayList.toArray(abc);

                // names.addAll(arrayList);
            } else {
                System.out.println("else");

                for (int i = 0; i < abc.length; i++) {

                    System.out.println(abc[i] + "----" + charText);

                    if (abc[i].toLowerCase(Locale.getDefault()).contains(charText)) {
                        names.add(abc[i]);
                    }
                }
                abc = new String[names.size()];
                abc = names.toArray(abc);
            }
            ad = new ArrayAdapter<String>(Search_Class.this,
                    android.R.layout.simple_list_item_1, abc);
            listview3.setAdapter(ad);
            ad.notifyDataSetChanged();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

    }

Just Created A Custom `Listview` Using `ListActivity` 

public class SearchingClass extends ListActivity {
    EditText et;
    ListView lv;
    Context context;
    ArrayList<String> AllSongs;
    String[] AllSongsArray;
    SongsManager songManager;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    SearchClass_Adapter adapter;
    int textlength = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searching_class);
        et = (EditText) findViewById(R.id.EditText01);
        lv = (ListView) findViewById(android.R.id.list);
        context = getBaseContext();
        songManager = new SongsManager();
        songsList = songManager.getPlayList(context);
        AllSongs = new ArrayList<String>();

        for (int i = 0; i < songsList.size(); i++) {
            HashMap<String, String> obj = songsList.get(i);

            AllSongs.add(obj.get("songTitle"));
        }
        AllSongsArray = new String[AllSongs.size()];
        AllSongsArray = AllSongs.toArray(AllSongsArray);
        setListAdapter(new bsAdapter(this));
        et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                // Abstract Method of TextWatcher Interface.
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // Abstract Method of TextWatcher Interface.
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                textlength = et.getText().length();
                AllSongs.clear();
                for (int i = 0; i < AllSongsArray.length; i++) {
                    if (textlength <= AllSongsArray[i].length()) {
                        /***
                         * If you want to highlight the countries which start
                         * with entered letters then choose this block. And
                         * comment the below If condition Block
                         */
                        /*
                         * if(et.getText().toString().equalsIgnoreCase( (String)
                         * listview_names[i].subSequence(0, textlength))) {
                         * array_sort.add(listview_names[i]);
                         * image_sort.add(listview_images[i]); }
                         */

                        /***
                         * If you choose the below block then it will act like a
                         * Like operator in the Mysql
                         */

                        if (AllSongsArray[i].toLowerCase().contains(
                                et.getText().toString().toLowerCase().trim())) {
                            AllSongs.add(AllSongsArray[i]);
                        }
                    }
                }
                AppendList(AllSongs);
            }

        });
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), AllSongs.get(position),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.searching_class, menu);
        return true;
    }

    public void AppendList(ArrayList<String> str) {
        setListAdapter(new bsAdapter(this));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public class bsAdapter extends BaseAdapter {
        Activity cntx;

        public bsAdapter(Activity context) {
            // TODO Auto-generated constructor stub
            this.cntx = context;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return AllSongs.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return AllSongs.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return AllSongs.size();
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {
            View row = null;

            LayoutInflater inflater = cntx.getLayoutInflater();
            row = inflater.inflate(R.layout.listview_item, null);

            TextView tv = (TextView) row.findViewById(R.id.tv_artist_name);

            tv.setText(AllSongs.get(position));

            return row;
        }
    }
}

这是我用来在搜索结果中突出显示搜索关键字的实用程序代码,希望这可以帮助您实现应用程序的某些部分

public void setTextAndhighLightSearchKeytest(String searchKey,String searchResult, TextView textView) {
    if (!TextUtils.isEmpty(searchKey) && !TextUtils.isEmpty(searchResult)) {
        String searchResultLowerCase  = searchResult.toLowerCase(Locale.UK);
        String searchKeyLowerCase  = searchKey.toLowerCase(Locale.UK);
        int start = searchResultLowerCase.indexOf(searchKeyLowerCase);
        int end = start + searchKey.length();

        if (start > -1 && start < searchResult.length() && end < searchResult.length()) {
            SpannableStringBuilder builder = new SpannableStringBuilder(searchResult);
            builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(builder, BufferType.SPANNABLE);
        }
    }
}
String your_val = filteredList.get(position).getYourValue();
        int startPos = your_val.indexOf(searchString.toUpperCase());
        int endPos = startPos + searchString.length();
        Spannable spanText = Spannable.Factory.getInstance().newSpannable(
                Your_value
        );

        if (startPos >= 0) {
            spanText.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(your_color)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }



        viewHolder.tvInfo.setText(spanText);

只需将此代码与您的值一起放入基本适配器的 getView 方法中

ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, abc){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                String your_val = filteredList.get(position).getYourValue();
                int startPos = your_val.indexOf(searchString.toUpperCase());
                int endPos = startPos + searchString.length();
                Spannable spanText = Spannable.Factory.getInstance().newSpannable(
                        Your_value
                );

                if (startPos >= 0) {
                    spanText.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(your_color)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spanText.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                viewHolder.tvInfo.setText(spanText);
                return your_view;
            }
        };

首先添加两个函数getData并将Data Search设置为baseadapter

   public class bsAdapter extends BaseAdapter {
    Activity cntx;

    public bsAdapter(Activity context) {
        // TODO Auto-generated constructor stub
        this.cntx = context;

    }

    public int getCount() {
        // TODO Auto-generated method stub
        return AllSongs.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return AllSongs.get(position);
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return AllSongs.size();
    }
    public void setDataSearch(String data) {
            this.search = data;
    } 

    public String getData() {
        return this.search;
    }

首先在Search_class

中声明searchData
public String searchData;
private bsAdapter mAdapter;

并声明

mAdapter = new bsAdapter(this);

然后你在文本观察器中添加条件

  public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            textlength = et.getText().length();
            AllSongs.clear();
            for (int i = 0; i < AllSongsArray.length; i++) {
                if (textlength <= AllSongsArray[i].length()) {
                    if (AllSongsArray[i].toLowerCase().contains(
                            et.getText().toString().toLowerCase().trim())) {
                        AllSongs.add(AllSongsArray[i]);
                    }
                }
              if (textlength == 0) {

                     mAdapter.setDataSearch(null);

                } else {

                    searchData = s.toString().toLowerCase();
                    mAdapter.setDataSearch(SearchData);
                }

         }
            AppendList(AllSongs);
        }

然后把这个函数放到baseadapter

public static CharSequence highlight(String search, String originalText) {

       String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\p{InCombiningDiacriticalMarks}+", "").toLowerCase();

       int start = normalizedText.indexOf(search);

       Spannable highlighted = new SpannableString(originalText);
        if (start < 0) {
            // not found, nothing to to
            return originalText;
        } else {

            while (start >= 0) {

                int spanStart   = Math.min(start, originalText.length());
                int spanEnd     = Math.min(start + search.length(), originalText.length());

                highlighted.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                highlighted.setSpan(new ForegroundColorSpan(cntx.getResources().getColor(R.color.text_color_white)), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                start = normalizedText.indexOf(search, spanEnd);
            }

            return highlighted;
        }
    }

然后把这个

public View getView(final int position, View convertView,
            ViewGroup parent) {
        View row = null;

        LayoutInflater inflater = cntx.getLayoutInflater();
        row = inflater.inflate(R.layout.listview_item, null);

        TextView tv = (TextView) row.findViewById(R.id.tv_artist_name);

        if(search != null){
                tv.setText(highlight(search,AllSongs.get(position));
            }
            else if (search == null){
                tv.setText(AllSongs.get(position));

            }


        return row;

所以我在这里纠正了代码并且工作正常...

public class SearchingClass extends ListActivity {
    EditText et;
    ListView lv;
    Context context;
    static ArrayList<String> AllSongs;
    String[] AllSongsArray;
    SongsManager songManager;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    int textlength = 0;
    public String SearchData;
    private bsAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searching_class);
        et = (EditText) findViewById(R.id.EditText01);
        lv = (ListView) findViewById(android.R.id.list);
        context = getBaseContext();
        songManager = new SongsManager();
        songsList = songManager.getPlayList(context);
        AllSongs = new ArrayList<String>();
        mAdapter = new bsAdapter(this);
        for (int i = 0; i < songsList.size(); i++) {
            HashMap<String, String> obj = songsList.get(i);

            AllSongs.add(obj.get("songTitle"));
        }
        AllSongsArray = new String[AllSongs.size()];
        AllSongsArray = AllSongs.toArray(AllSongsArray);
        setListAdapter(new bsAdapter(this));
        et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

                textlength = et.getText().length();
                AllSongs.clear();
                for (int i = 0; i < AllSongsArray.length; i++) {
                    if (textlength <= AllSongsArray[i].length()) {
                        if (AllSongsArray[i].toLowerCase().contains(
                                et.getText().toString().toLowerCase().trim())) {
                            AllSongs.add(AllSongsArray[i]);
                        }
                    }
                    if (textlength == 0) {

                        mAdapter.setDataSearch(null);

                    } else {

                        SearchData = s.toString().toLowerCase();
                        mAdapter.setDataSearch(SearchData);
                    }

                }
                AppendList(AllSongs);
            }

        });
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), AllSongs.get(position),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.searching_class, menu);
        return true;
    }

    public void AppendList(ArrayList<String> str) {
        setListAdapter(new bsAdapter(this));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class bsAdapter extends BaseAdapter {
        static Activity cntx;
        static String search;
        String value;

        public bsAdapter(Activity context) {
            // TODO Auto-generated constructor stub
            this.cntx = context;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return AllSongs.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return AllSongs.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return AllSongs.size();
        }

        public void setDataSearch(String data) {
            System.out.println("recieved value" + data);
            this.search = data;
        }

        public String getData() {
            return this.search;
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {
            View row = null;
            LayoutInflater inflater = cntx.getLayoutInflater();
            row = inflater.inflate(R.layout.listview_item, null);
            TextView tv = (TextView) row.findViewById(R.id.tv_artist_name);
            // tv.setText(AllSongs.get(position));
            System.out.println("search data value" + search);

            if (search != null) {

                tv.setText(highlight(search, AllSongs.get(position)));
            } else if (search == null) {
                tv.setText(AllSongs.get(position));

            }

            return row;
        }

        public CharSequence highlight(String search, String originalText) {

            String normalizedText = Normalizer
                    .normalize(originalText, Normalizer.Form.NFD)
                    .replaceAll("\p{InCombiningDiacriticalMarks}+", "")
                    .toLowerCase();

            int start = normalizedText.indexOf(search);

            Spannable highlighted = new SpannableString(originalText);
            if (start < 0) {
                // not found, nothing to to
                return originalText;
            } else {

                while (start >= 0) {

                    int spanStart = Math.min(start, originalText.length());
                    int spanEnd = Math.min(start + search.length(),
                            originalText.length());

                    highlighted.setSpan(new StyleSpan(
                            android.graphics.Typeface.BOLD), spanStart,
                            spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    highlighted.setSpan(new ForegroundColorSpan(cntx
                            .getResources().getColor(R.color.red)), spanStart,
                            spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    start = normalizedText.indexOf(search, spanEnd);
                }

                return highlighted;
            }
        }
    }